void CreateDefaultFile()
        {
            JArray jArray = new JArray();
            jArray.Add(JsonConvert.SerializeObject(BacklogItem1));
            jArray.Add(JsonConvert.SerializeObject(BacklogItem2));
            jArray.Add(JsonConvert.SerializeObject(BacklogItem3));

            JObject jObject = new JObject();
            jObject["BacklogItems"] = jArray;

            string jsonString = jObject.ToString();

            PathHelper.WriteFile(filePath, jsonString);
        }
        public void GetColumnsFromItemsFallthroughNullTest()
        {
            JArray array = new JArray();
            array.Add(new JObject()
            {
                { "integer", 1 },
                { "value1", "string"},
                { "boolean", true },
                { "null", null }

            });
            array.Add(new JObject()
            {
                { "integer", 1 },
                { "value1", "string"},
                { "boolean", true },
                { "null", DateTime.Now }
            });

            IDictionary<string, Column> cols = storage.GetColumnsFromItems(array);

            Assert.AreEqual(4, cols.Count);

            Assert.IsTrue(cols.ContainsKey("integer"));
            // json.net makes int long
            Assert.AreEqual(typeof(long), cols["integer"].GetClrDataType());
            Assert.IsTrue(cols.ContainsKey("value1"));
            Assert.AreEqual(typeof(string), cols["value1"].GetClrDataType());
            Assert.IsTrue(cols.ContainsKey("boolean"));
            Assert.AreEqual(typeof(bool), cols["boolean"].GetClrDataType());
            Assert.IsTrue(cols.ContainsKey("null"));
            Assert.AreEqual(typeof(DateTime), cols["null"].GetClrDataType());
        }
Ejemplo n.º 3
1
        public void FormatPropertyInJson()
        {
            JObject query = new JObject();
            JProperty orderProp = new JProperty("order", "breadth_first");
            query.Add(orderProp);

            JObject returnFilter = new JObject();
            returnFilter.Add("body", new JValue("position.endNode().getProperty('name').toLowerCase().contains('t')"));
            returnFilter.Add("language", new JValue("javascript"));

            query.Add("return_filter", new JValue(returnFilter.ToString()));

            JObject pruneEval = new JObject();
            pruneEval.Add("body", new JValue("position.length() > 10"));
            pruneEval.Add("language", new JValue("javascript"));
            query.Add("prune_evaluator", pruneEval.ToString());

            query.Add("uniqueness", new JValue("node_global"));

            JArray relationships = new JArray();
            JObject relationShip1 = new JObject();
            relationShip1.Add("direction", new JValue("all"));
            relationShip1.Add("type", new JValue("knows"));
            relationships.Add(relationShip1);

            JObject relationShip2 = new JObject();
            relationShip2.Add("direction", new JValue("all"));
            relationShip2.Add("type", new JValue("loves"));
            relationships.Add(relationShip2);

            query.Add("relationships", relationships.ToString());
            //arr.Add(
            Console.WriteLine(query.ToString());
            //Assert.AreEqual(@"""order"" : ""breadth_first""", jobject.ToString());
        }
            public static void UnparseEntities(JObject obj, IEnumerable<IEmbeddedLink> ELinks, IEnumerable<IEmbeddedRepresentation> EReps)
            {
                var anyLinks = ELinks != null && ELinks.Any();
                var anyReps = EReps != null && EReps.Any();

                if (anyLinks || anyReps)
                {
                    var entities = new JArray();

                    if (anyReps)
                    {
                        foreach (var rep in EReps)
                        {
                            entities.Add(UnparseEmbeddedRepresentation(rep));
                        }
                    }

                    if (anyLinks)
                    {
                        foreach (var link in ELinks)
                        {
                            entities.Add(UnparseEmbeddedLink(link));
                        }
                    }

                    obj[ENTITIES] = entities;
                }
            }
Ejemplo n.º 5
0
        private static JObject GetJObject(object source, Type type = null)
        {
            var dictionary = new JObject();
            var types = type ?? source.GetType();

            var attrs = GetTopAttributes(types);
            var properties = types.GetProperties();

            foreach (var property in properties)
            {
                if (attrs.ContainsKey(property.Name))
                {
                    var v = property.GetValue(source, null);

                    var attr = attrs[property.Name];
                    if (v == null)
                    {
                        dictionary.Add(attr.ItemName, null);
                        continue;
                    }

                    if (string.IsNullOrEmpty(attr.ListName))
                    {
                        var vType = v.GetType();
                        if (vType.IsPrimitive || vType.IsValueType || vType == typeof(string))
                        {
                            dictionary.Add(attr.ItemName, new JValue(property.GetValue(source, null)));
                        }
                        else
                        {
                            dictionary.Add(new JProperty(attr.ItemName, GetJObject(property.GetValue(source, null))));
                        }
                    }
                    else
                    {
                        var tempObjs = property.GetValue(source, null);
                        if (tempObjs is IList)
                        {
                            var array = new JArray();
                            foreach (var i in tempObjs as IList)
                            {
                                var iType = i.GetType();
                                if (iType.IsPrimitive || iType.IsValueType || iType == typeof(string))
                                {
                                    array.Add(new JValue(i));
                                }
                                else
                                {
                                    array.Add(GetJObject(i));
                                }
                            }

                            dictionary.Add(new JProperty(attr.ListName, new JObject(new JProperty(attr.ItemName, array))));
                        }
                    }
                }
            }

            return dictionary;
        }
Ejemplo n.º 6
0
        public IHttpActionResult Get(string name)
        {
            var json = string.Empty;
            var account = CloudStorageAccount.Parse(Config.Get("DeepStorage.OutputConnectionString"));
            var blobClient = account.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(Config.Get("DeepStorage.HdpContainerName"));

            var prefix = string.Format("{0}.json/part-r-", name);
            var matchingBlobs = container.ListBlobs(prefix, true);
            foreach (var part in matchingBlobs.OfType<CloudBlockBlob>())
            {
                json += part.DownloadText() + Environment.NewLine;
            }

            var outputArray = new JArray();
            foreach (var line in json.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
            {
                dynamic raw = JObject.Parse(line);
                var formatted = new JArray();
                formatted.Add((string)raw.eventName);
                formatted.Add((long)raw.count);
                outputArray.Add(formatted);
            }

            return Ok(outputArray);
        }
Ejemplo n.º 7
0
 //{{},{}}
 JArray newLine(JObject coord,JObject coord2)
 {
     JArray  line = new JArray();
     line.Add(coord);
     line.Add(coord2);
     return line;
 }
Ejemplo n.º 8
0
 public object ToJson()
 {
     var json = new JArray();
     json.Add("face");
     json.Add(Id);
     return json;
 }
Ejemplo n.º 9
0
        private string GetTestRestQuery()
        {
            JObject query = new JObject();
            JProperty orderProp = new JProperty("order", "breadth_first");
            query.Add(orderProp);

            JObject returnFilter = new JObject();
            returnFilter.Add("body", new JValue("position.endNode().getProperty('FirstName').toLowerCase().contains('sony')"));
            returnFilter.Add("language", new JValue("javascript"));
            JProperty filter = new JProperty("return_filter", returnFilter);
            query.Add(filter);

            JArray relationships = new JArray();
            JObject relationShip1 = new JObject();
            relationShip1.Add("direction", new JValue("out"));
            relationShip1.Add("type", new JValue("wife"));
            relationships.Add(relationShip1);

            JObject relationShip2 = new JObject();
            relationShip2.Add("direction", new JValue("all"));
            relationShip2.Add("type", new JValue("loves"));
            relationships.Add(relationShip2);
            JProperty relationShipProp = new JProperty("relationships", relationships);

            query.Add(relationShipProp);

            JProperty uniqueness = new JProperty("uniqueness", "node_global");
            query.Add(uniqueness);
            JProperty maxDepth = new JProperty("max_depth", 2);
            query.Add(maxDepth);
            return query.ToString();
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JArray array = new JArray();
            IList list = (IList)value;
            if (list.Count > 0)
            {
                JArray keys = new JArray();

                JObject first = JObject.FromObject(list[0], serializer);
                foreach (JProperty prop in first.Properties())
                {
                    keys.Add(new JValue(prop.Name));
                }
                array.Add(keys);

                foreach (object item in list)
                {
                    JObject obj = JObject.FromObject(item, serializer);
                    JArray itemValues = new JArray();
                    foreach (JProperty prop in obj.Properties())
                    {
                        itemValues.Add(prop.Value);
                    }
                    array.Add(itemValues);
                }
            }
            array.WriteTo(writer);
        }
Ejemplo n.º 11
0
        public JArray serializeArray()
        {
            JArray verticesNode = new JArray();

            if(vertices[0] != null)
            {
                verticesNode.Add(vertices[0].serializeObject());
            }

            if(vertices[1] != null)
            {
                verticesNode.Add(vertices[1].serializeObject());
            }

            if(vertices[2] != null)
            {
                verticesNode.Add(vertices[2].serializeObject());
            }

            if(verticesNode.Count > 0)
            {
                return verticesNode;
            }

            return null;
        }
Ejemplo n.º 12
0
 public virtual byte[] GetExceptionResponse(Exception ex)
 {
     JToken jresult = JToken.FromObject(ex.Message);
     JArray response = new JArray();
     response.Add("ERR");
     response.Add(jresult);
     return Encoding.UTF8.GetBytes(response.ToString(Formatting.None));
 }
Ejemplo n.º 13
0
 public void JArray_Should_Support_Complex_Types()
 {
     var arry = new JArray();
     arry.Add(1);
     arry.Add("abc");
     var result = arry.ToString(Formatting.None);
     Assert.AreEqual("[1,\"abc\"]", result);
 }
Ejemplo n.º 14
0
 public object ToJson()
 {
     // [\"cface\",\"group\",\"5F7E31F0001EF4310865F1FF4549B12B.jPg\"]
     var json = new JArray();
     json.Add("cface");
     json.Add("group");
     json.Add(FileName);
     return json;
 }
Ejemplo n.º 15
0
 public static byte[] CreateCallMessage(string callID, string methodName, params object[] args)
 {
     var message = new JArray();
     message.Add(2);
     message.Add(callID);
     message.Add(methodName);
     message.Add(JArray.FromObject(args));
     return Encoding.UTF8.GetBytes(message.ToString(Formatting.None));
 }
Ejemplo n.º 16
0
        public virtual byte[] GetOKResponse(object returnValue)
        {
            JToken jresult = (returnValue == null) ? new JRaw("null") : JToken.FromObject(returnValue);

            JArray response = new JArray();
            response.Add("OK");
            response.Add(jresult);
            return Encoding.UTF8.GetBytes(response.ToString(Formatting.None));
        }
Ejemplo n.º 17
0
        public static async Task Save(IDictionary<string, JObject> metadata, Stream packageStream, string storagePrimary, string storageContainerPackages)
        {
            string root = Guid.NewGuid().ToString();

            IList<Task<Tuple<string, Uri, Stream>>> tasks = new List<Task<Tuple<string, Uri, Stream>>>();

            using (ZipArchive archive = new ZipArchive(packageStream, ZipArchiveMode.Read, true))
            {
                foreach (ZipArchiveEntry zipEntry in archive.Entries)
                {
                    using (Stream zipEntryStream = zipEntry.Open())
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        zipEntryStream.CopyTo(memoryStream);
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        tasks.Add(SaveFile(memoryStream, root + "/package", zipEntry.FullName, storagePrimary, storageContainerPackages));
                    }
                }
            }

            await Task.WhenAll(tasks.ToArray());

            JArray entries = new JArray();

            foreach (Task<Tuple<string, Uri, Stream>> task in tasks)
            {
                JObject entry = new JObject();

                entry["fullName"] = task.Result.Item1;
                entry["location"] = task.Result.Item2.ToString();

                entries.Add(entry);

                task.Result.Item3.Dispose();
            }

            packageStream.Seek(0, SeekOrigin.Begin);
            Tuple<string, Uri, Stream> packageEntry = await SaveFile(packageStream, root, "package.zip", storagePrimary, storageContainerPackages);

            string packageContent = packageEntry.Item2.ToString();

            JObject packageItem = new JObject
            {
                { "@type", new JArray { MetadataHelpers.GetName(Schema.DataTypes.Package, Schema.Prefixes.NuGet), MetadataHelpers.GetName(Schema.DataTypes.ZipArchive, Schema.Prefixes.NuGet) } },
                { "location", packageContent },
                { "size", packageStream.Length },
                { "hash", Utils.GenerateHash(packageStream) }
            };

            entries.Add(packageItem);

            metadata["inventory"] = new JObject
            { 
                { "entries", entries },
                { "packageContent", packageContent }
            };
        }
Ejemplo n.º 18
0
 public static byte[] CreateEventMessage(string eventType, object ev)
 {
     JToken jev = JToken.FromObject(ev);
     var message = new JArray();
     message.Add(8);
     message.Add(eventType);
     message.Add(jev);
     return Encoding.UTF8.GetBytes(message.ToString(Formatting.None));
 }
Ejemplo n.º 19
0
 /// 
 ///  name:"",geoCoord:[110, 296.913]
 /// 
 /// 
 JObject newPoint(geopoint g)
 {
     JArray xy = new JArray();
     xy.Add(g.x*s1);
     xy.Add(g.y*s2);
     return new JObject(
         new JProperty("geoCoord",xy),
         new JProperty("name",g.name)
         );
 }
Ejemplo n.º 20
0
 public object ToJson()
 {
     // [\"offpic\",\"/27d736df-2a59-4007-8701-7218bc70898d\",\"Beaver.bmp\",14173]
     JArray json = new JArray();
     json.Add("offpic");
     json.Add(FilePath);
     json.Add(FileName);
     json.Add(FileSize);
     return json;
 }
Ejemplo n.º 21
0
        public async Task<IEnumerable<ReleaseInfo>> PerformQuery(TorznabQuery query)
        {
            var searchString = query.GetQueryString();
            var releases = new List<ReleaseInfo>();

            var parameters = new JArray();
            parameters.Add(new JValue(configData.Key.Value));
            parameters.Add(new JValue(searchString.Trim()));
            parameters.Add(new JValue(100));
            parameters.Add(new JValue(0));
            var response = await PostDataWithCookiesAndRetry(APIBASE, null, null, null, new Dictionary<string, string>()
            {
                { "Accept", "application/json-rpc, application/json"},
                {"Content-Type", "application/json-rpc"}
            }, JsonRPCRequest("getTorrents", parameters),false);

            try
            {
                var btnResponse = JsonConvert.DeserializeObject<BTNRPCResponse>(response.Content);

                if (btnResponse != null && btnResponse.Result != null)
                {
                    foreach (var itemKey in btnResponse.Result.Torrents)
                    {
                        var btnResult = itemKey.Value;
                        var item = new ReleaseInfo();
                        if (!string.IsNullOrEmpty(btnResult.SeriesBanner))
                            item.BannerUrl = new Uri(btnResult.SeriesBanner);
                        item.Category = TorznabCatType.TV.ID;
                        item.Comments = new Uri($"https://broadcasthe.net/torrents.php?id={btnResult.GroupID}&torrentid={btnResult.TorrentID}");
                        item.Description = btnResult.ReleaseName;
                        item.Guid = new Uri(btnResult.DownloadURL);
                        if (!string.IsNullOrWhiteSpace(btnResult.ImdbID))
                            item.Imdb = ParseUtil.CoerceLong(btnResult.ImdbID);
                        item.Link = new Uri(btnResult.DownloadURL);
                        item.MinimumRatio = 1;
                        item.PublishDate = DateTimeUtil.UnixTimestampToDateTime(btnResult.Time);
                        item.RageID = btnResult.TvrageID;
                        item.Seeders = btnResult.Seeders;
                        item.Peers = btnResult.Seeders + btnResult.Leechers;
                        item.Size = btnResult.Size;
                        item.TVDBId = btnResult.TvdbID;
                        item.Title = btnResult.ReleaseName;
                        releases.Add(item);
                    }
                }

            }
            catch (Exception ex)
            {
                OnParseError(response.Content, ex);
            }
            return releases;
        }
Ejemplo n.º 22
0
        public string T()
        {
            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();
            return json;
        }
Ejemplo n.º 23
0
        public override byte[] GetExceptionResponse(Exception ex)
        {
            if (requestId == null || requestId.Type == JTokenType.Null)
                return null;

            JToken jresult = JToken.FromObject(ex.Message);
            JArray response = new JArray();
            response.Add(4);
            response.Add(requestId);
            response.Add(jresult);

            return Encoding.UTF8.GetBytes(response.ToString(Formatting.None));
        }
Ejemplo n.º 24
0
		public void PublishEvent(string topic, string publishID) {
			foreach (WAMPClient c in clients) {
				if (c.subscribedTopics.ContainsKey(topic)) {
					JArray packet = new JArray();
					packet.Add (WAMPMessageType.EVENT);
					packet.Add (c.subscribedTopics[topic]);
					packet.Add (publishID);
					packet.Add (new JObject());
					c.Send(packet.ToString());
				}
			}

		}
Ejemplo n.º 25
0
        private void SelecFilmByGenre(bool minusFilter = true, string minusFilterValue = "мульт")
        {
            Newtonsoft.Json.Linq.JArray  temp    = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JObject tempObj = new Newtonsoft.Json.Linq.JObject();
            string genre = "";

            foreach (var j in allFilm)
            {
                try
                {
                    tempObj = j["ThisCard"] as Newtonsoft.Json.Linq.JObject;
                    genre   = tempObj.Value <string>("Genre").ToLower();
                    if (genre.Contains(selectedGenre) || string.IsNullOrEmpty(selectedGenre))
                    {
                        if (minusFilter)
                        {
                            if (!genre.Contains(minusFilterValue))
                            {
                                temp.Add(j);
                            }
                        }
                        else
                        {
                            temp.Add(j);
                        }
                    }
                }
                catch
                {
                    continue;
                }
            }

            Films = new JObject[temp.Count];



            int u = 0;

            foreach (var t in temp)
            {
                Films[u] = (JObject)t;
                u++;
            }

            if (Films.Length > 0)
            {
                SetSelectedFilms(0);
                label5.Text = Films.Length.ToString();
            }
        }
Ejemplo n.º 26
0
        public override byte[] GetOKResponse(object returnValue)
        {
            if (requestId == null || requestId.Type == JTokenType.Null)
                return null;

            JToken jresult = (returnValue == null) ? new JRaw("null") : JToken.FromObject(returnValue);

            JArray response = new JArray();
            response.Add(3);
            response.Add(requestId);
            response.Add(jresult);

            return Encoding.UTF8.GetBytes(response.ToString(Formatting.None));
        }
Ejemplo n.º 27
0
        private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {

                JArray memberArray = new JArray();
                memberArray.Add(App._userid);
                memberArray.Add(App._reuserid);
                App.connectView.sendMesS(App._userid, false, enter.Text, 1, App._username, memberArray, Convert.ToString(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond));
                enter.Text = "";
                ContactListBox.SelectedIndex = App.ViewModel.Items.Count() - 1;
                ContactListBox.Focus();
            }
        }
    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)\/"
      // ]
    }
Ejemplo n.º 29
0
    public void AddToSelf()
    {
      JArray a = new JArray();
      a.Add(a);

      Assert.IsFalse(ReferenceEquals(a[0], a));
    }
Ejemplo n.º 30
0
        public async static Task <bool> SendMessageAsync(string receiverId, string message)
        {
            try
            {
                AddResponse(receiverId, message);

                Newtonsoft.Json.Linq.JObject updateInformation = new Newtonsoft.Json.Linq.JObject();

                updateInformation.Add("SenderId", App.ViewModel.CurrentUser.InstallationId);
                updateInformation.Add("ReceiverId", receiverId);
                updateInformation.Add("Message", message);

                Newtonsoft.Json.Linq.JArray tags = new Newtonsoft.Json.Linq.JArray();

                tags.Add(receiverId);

                updateInformation.Add("Tags", tags);

                JToken result = await FavoritesManager.DefaultManager.CurrentClient.InvokeApiAsync("sendShortMessageToTag", updateInformation);
            }
            catch (Exception ex)
            {
            }

            return(true);
        }
Ejemplo n.º 31
0
        public static Tuple<string, string> SplitShowsByGenre(string json, string genre)
        {
            JArray selectedShowsJson = new JArray();
            JArray otherShowsJson = new JArray();

            foreach (JObject showJson in JArray.Parse(json))
            {
                bool genreFound = false;
                foreach (JValue genreJson in showJson.Value<JArray>("genres"))
                {
                    if (genreJson.ToString() == genre)
                    {
                        selectedShowsJson.Add(showJson);
                        genreFound = true;
                        break;
                    }
                }
                if (!genreFound)
                {
                    otherShowsJson.Add(showJson);
                }
            }

            return new Tuple<string, string>(selectedShowsJson.ToString(Formatting.None), otherShowsJson.ToString(Formatting.None));
        }
Ejemplo n.º 32
0
        public static void GetTranslations(TranslateCommand translateCommand)
        {
            foreach (string lang in translateCommand.Translations.Keys)
            {
                int counter = 0;
                Newtonsoft.Json.Linq.JArray requestTexts = new Newtonsoft.Json.Linq.JArray();

                while (counter <= 24 && counter < translateCommand.Translations[lang].Stories.Count)
                {
                    JObject text = new JObject();
                    text.Add("Text", translateCommand.Translations[lang].Stories[counter].Title);
                    requestTexts.Add(text);
                    counter++;
                }

                List <string> translations = GetTranslation(requestTexts, lang, translateCommand.DisplayLanguage).Result;

                if (translations.Count > 0)
                {
                    for (int i = 0; i < translations.Count; i++)
                    {
                        translateCommand.Translations[lang].Stories[i].TranslatedTitle = translations[i];
                    }
                }
            }
        }
Ejemplo n.º 33
0
    static int Add(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <Newtonsoft.Json.Linq.JToken>(L, 2))
            {
                Newtonsoft.Json.Linq.JArray obj  = (Newtonsoft.Json.Linq.JArray)ToLua.CheckObject <Newtonsoft.Json.Linq.JArray>(L, 1);
                Newtonsoft.Json.Linq.JToken arg0 = (Newtonsoft.Json.Linq.JToken)ToLua.ToObject(L, 2);
                obj.Add(arg0);
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes <object>(L, 2))
            {
                Newtonsoft.Json.Linq.JArray obj = (Newtonsoft.Json.Linq.JArray)ToLua.CheckObject <Newtonsoft.Json.Linq.JArray>(L, 1);
                object arg0 = ToLua.ToVarObject(L, 2);
                obj.Add(arg0);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Newtonsoft.Json.Linq.JArray.Add"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Ejemplo n.º 34
0
        public async Task TestCase()
        {
            Client c = new Client(userName, apiKey);

            Configuration.Arguments cfArgs = new Configuration.Arguments();
            cfArgs.Add("name", "configuration bindings test");
            Newtonsoft.Json.Linq.JObject configs = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JObject any     = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("test");
            any.Add("tags", tags);
            configs.Add("any", any);

            cfArgs.Add("configurations", configs);
            Configuration cf = await c.CreateConfiguration(cfArgs);

            Ordered <Configuration.Filterable, Configuration.Orderable, Configuration> result
                = (from cfg in c.ListConfigurations()
                   orderby cfg.Created descending
                   select cfg);
            Listing <Configuration> configurations = await result;

            if (configurations.Meta.TotalCount == 0)
            {
                throw new System.Exception("Creation not created or not listed");
            }

            cf = await c.Update <Configuration>(cf.Resource, "renamed configuration");

            await c.Delete(cf);
        }
Ejemplo n.º 35
0
 public override JToken getOutput()
 {
     Newtonsoft.Json.Linq.JArray timeArray = new Newtonsoft.Json.Linq.JArray();
     for (int ii = 0; ii < TimeSeriesLength; ++ii)
     {
         o_TimeSeriesIndex = ii;
         timeArray.Add(new Newtonsoft.Json.Linq.JArray(Value));
     }
     resetTimeSeries();
     return(timeArray);
 }
Ejemplo n.º 36
0
        public async Task CreateDeepnetFromRemoteSource()
        {
            // Prepare connection
            Client c = new Client(userName, apiKey);

            // Create source
            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "http://static.bigml.com/csv/iris.csv");
            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            // Create dataset
            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            // Create deepnet
            Deepnet.Arguments argsDn = new Deepnet.Arguments();
            argsDn.Add("dataset", ds.Resource);
            Deepnet dn = await c.CreateDeepnet(argsDn);

            dn = await c.Wait <Deepnet>(dn.Resource);

            Assert.AreEqual(dn.StatusMessage.StatusCode, Code.Finished);

            // test UPDATE method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            dn = await c.Update <Deepnet>(dn.Resource, changes);

            Assert.AreEqual(dn.Code, System.Net.HttpStatusCode.Accepted);

            // test DELETE method
            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(dn);
        }
Ejemplo n.º 37
0
        public async Task CreateLogisticRegressionFromRemoteSource()
        {
            Client c = new Client(userName, apiKey);

            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "https://static.bigml.com/csv/iris.csv");
            args.Add("name", "C# tests - Iris");

            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            LogisticRegression.Arguments argsTM = new LogisticRegression.Arguments();
            argsTM.Add("dataset", ds.Resource);
            LogisticRegression lr = await c.CreateLogisticRegression(argsTM);

            lr = await c.Wait <LogisticRegression>(lr.Resource);

            // test it is finished
            Assert.AreEqual(lr.StatusMessage.StatusCode, Code.Finished);

            // test update method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            lr = await c.Update <LogisticRegression>(lr.Resource, changes);

            Assert.AreEqual(lr.Code, System.Net.HttpStatusCode.Accepted);

            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(lr);
        }
Ejemplo n.º 38
0
        static JArray CallScript(byte[] script)
        {
            if (wc == null)
            {
                wc = new System.Net.WebClient();
            }
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "invokescript";
            var _params = new Newtonsoft.Json.Linq.JArray();

            _params.Add(ThinNeo.Helper.Bytes2HexString(script));
            upparam["params"] = _params;

            var info   = wc.UploadString(url, upparam.ToString());
            var result = JObject.Parse(info)["result"]["stack"] as JArray;

            return(result);
            //Console.WriteLine(info);
        }
Ejemplo n.º 39
0
        void DoCallTran(ThinNeo.Transaction tx)
        {
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "sendrawtransaction";
            var _params = new Newtonsoft.Json.Linq.JArray();

            var data = tx.GetRawData();

            _params.Add(ThinNeo.Helper.Bytes2HexString(data));
            upparam["params"] = _params;

            var info = wc.UploadString(url, upparam.ToString());

            Console.WriteLine(info);

            var   txid = tx.GetHash();
            State s    = new State();

            s.state = 0;
            mapTxState[txid.ToString()] = s;
        }
Ejemplo n.º 40
0
        private void SendReturn(string txid, ReturnInfo ret)
        {
            //L2CmHCqgeNHL1i9XFhTLzUXsdr5LGjag4d56YY98FqEi4j5d83Mv
            var prikey     = ThinNeo.Helper.GetPrivateKeyFromWIF("L1WHHa4zmudqzRTYQiF4wbw9duiqEvcz7QY93GG1rzvCVxFVSDud");
            var pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            var scripthash = ThinNeo.Helper.GetScriptHashFromPublicKey(pubkey);
            var addres     = ThinNeo.Helper.GetAddressFromScriptHash(scripthash);

            ThinNeo.Transaction tx = new ThinNeo.Transaction();
            tx.inputs  = new ThinNeo.TransactionInput[0];
            tx.outputs = new ThinNeo.TransactionOutput[0];
            tx.type    = ThinNeo.TransactionType.InvocationTransaction;
            tx.version = 1;
            //附加一个见证人  ///要他签名
            tx.attributes          = new ThinNeo.Attribute[1];
            tx.attributes[0]       = new ThinNeo.Attribute();
            tx.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
            tx.attributes[0].data  = scripthash;

            //拼接调用脚本
            var invokedata = new ThinNeo.InvokeTransData();

            tx.extdata     = invokedata;
            invokedata.gas = 0;
            var sb = new ThinNeo.ScriptBuilder();

            MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
            array.AddArrayValue("(hex256)" + txid);         //txid
            array.AddArrayValue("(int)" + ret.returnvalue); //returnvalue
            var _params = new MyJson.JsonNode_Array();

            array.Add(_params);//params
            Random r = new Random();

            _params.AddArrayValue("(int)" + r.Next());

            sb.EmitParamJson(array);
            sb.EmitPushString("returnvalue");
            ThinNeo.Hash160 contractaddr = new ThinNeo.Hash160("0x24192c2a72e0ce8d069232f345aea4db032faf72");
            sb.EmitAppCall(contractaddr);
            invokedata.script = sb.ToArray();

            //签名 (谁来签名)
            var msg  = tx.GetMessage();
            var data = ThinNeo.Helper.Sign(msg, prikey);

            tx.AddWitness(data, pubkey, addres);

            System.Net.WebClient wc = new System.Net.WebClient();

            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "sendrawtransaction";
            var _vparams = new Newtonsoft.Json.Linq.JArray();

            var vdata = tx.GetRawData();

            _vparams.Add(ThinNeo.Helper.Bytes2HexString(vdata));
            upparam["params"] = _vparams;

            var strdata = upparam.ToString(Formatting.None);
            var info    = wc.UploadString(url, strdata);
            //Console.WriteLine(info);
            var this_txid = tx.GetHash();

            ret.txid = this_txid.ToString();
            ret.rsp  = info;
            this.list2.Items.Add(ret);
        }
Ejemplo n.º 41
0
        public ActionResult GetBatchPrint(string ticketid)
        {
            String tickets = "'" + ticketid.Replace(",", "','") + "'";

            //获取全部发票明细数据
            DataTable dts = feeticketbll.GetBatchPrint(tickets);

            var data = new Newtonsoft.Json.Linq.JArray();

            //发票按照号码、税率分组
            DataTable dtgroup = dts.DefaultView.ToTable(true, "ticket_id", "taxrate");

            for (int i = 0; i < dtgroup.Rows.Count; i++)
            {
                string  tmpticketid = dtgroup.Rows[i][0].ToString() + "_s" + i.ToString();                     //分组临时发票号
                string  bz          = "";                                                                      //发票备注
                decimal hjje        = 0;                                                                       //合计金额
                decimal hjse        = 0;                                                                       //合计税额
                decimal sl          = Convert.ToDecimal(dtgroup.Rows[i][1].ToString().Replace("%", "")) / 100; //税率
                decimal se          = 0;
                string  khmc        = "";                                                                      //客户名称
                string  khdm        = "";                                                                      //客户代码
                string  khsh        = "";                                                                      //客户税号
                string  khdz        = "";                                                                      //客户地址
                string  khkhyhzh    = "";                                                                      //客户开户银行账号

                var jarray = new Newtonsoft.Json.Linq.JArray();



                DataRow[] rows = dts.Select("ticket_id='" + dtgroup.Rows[i][0] + "' and taxrate='" + dtgroup.Rows[i][1] + "'");
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        //赋值及合计
                        khmc     = row["khmc"].ToString();
                        khdm     = row["khdm"].ToString();
                        khdz     = row["khdz"].ToString();
                        khsh     = row["khsh"].ToString();
                        khkhyhzh = row["khkhyhzh"].ToString();
                        hjje    += Convert.ToDecimal(row["check_money"]);
                        se       = Math.Round(Convert.ToDecimal(row["check_money"]) * sl / (1 + sl), 2);
                        hjse    += se;
                        if (bz.IndexOf(row["feeitem_name"].ToString()) > 0)
                        {
                            bz = bz + "," + row["fperiod"].ToString() + ",";
                        }
                        else
                        {
                            bz = row["feeitem_name"].ToString() + ":" + row["fperiod"].ToString() + ",";
                        }

                        //构建子json 行数据rowitems{feeitemname,dispname,taxtype,taxrate,fmoney,speriod,se}
                        var childjson = new Newtonsoft.Json.Linq.JObject();
                        childjson.Add("feeitemname", row["feeitem_name"].ToString());
                        childjson.Add("feedispname", row["feedispname"].ToString());
                        childjson.Add("taxtype", row["taxtype"].ToString());
                        childjson.Add("taxrate", row["taxrate"].ToString());
                        childjson.Add("fmoney", row["check_money"].ToString());
                        childjson.Add("fperiod", row["fperiod"].ToString());

                        jarray.Add(childjson);
                    }
                }
                //构建主json 数据 {tmpticketid,khdm,khmc,khsh,khdz,khkhyhzh,hjje,hjse,bhsje,bz}
                var jsondata = new JObject();
                jsondata.Add("tmpticketid", tmpticketid);
                jsondata.Add("khdm", khdm);
                jsondata.Add("khmc", khmc);
                jsondata.Add("khsh", khsh);
                jsondata.Add("khdz", khdz);
                jsondata.Add("khkhyhzh", khkhyhzh);
                jsondata.Add("hjje", hjje);
                jsondata.Add("hjse", hjse);
                jsondata.Add("bhsje", hjje - hjse);
                jsondata.Add("bz", bz);
                jsondata.Add("feeitems", jarray);

                data.Add(jsondata);
            }
            //返回构造的json数据
            return(ToJsonResult(data));
        }
Ejemplo n.º 42
0
        public async Task CreateFusionFromRemoteSource()
        {
            // Prepare connection
            Client c = new Client(userName, apiKey);

            // Create source
            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "http://static.bigml.com/csv/iris.csv");
            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            // Create dataset
            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            // Create Logistic Regression
            LogisticRegression.Arguments argsLR = new LogisticRegression.Arguments();
            argsLR.Add("dataset", ds.Resource);
            LogisticRegression lr = await c.CreateLogisticRegression(argsLR);

            lr = await c.Wait <LogisticRegression>(lr.Resource);

            // Create Tree model
            Model.Arguments argsMd = new Model.Arguments();
            argsMd.Add("dataset", ds.Resource);
            Model md = await c.CreateModel(argsMd);

            md = await c.Wait <Model>(md.Resource);

            // Create Fusion
            Fusion.Arguments argsFs = new Fusion.Arguments();
            System.Collections.Generic.List <dynamic> modelIDs = new System.Collections.Generic.List <dynamic>();
            modelIDs.Add(lr.Resource);
            modelIDs.Add(md.Resource);
            argsFs.Models = modelIDs;
            Fusion fs = await c.CreateFusion(argsFs);

            fs = await c.Wait <Fusion>(fs.Resource);

            Assert.AreEqual(fs.StatusMessage.StatusCode, Code.Finished);

            // test UPDATE method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            fs = await c.Update <Fusion>(fs.Resource, changes);

            Assert.AreEqual(fs.Code, System.Net.HttpStatusCode.Accepted);

            // test DELETE method
            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(fs);
        }
Ejemplo n.º 43
-1
        public async Task Run()
        {
            // Gather download count data from statistics warehouse
            IReadOnlyCollection<DownloadCountData> downloadData;
            Trace.TraceInformation("Gathering Download Counts from {0}/{1}...", StatisticsDatabase.DataSource, StatisticsDatabase.InitialCatalog);
            using (var connection = await StatisticsDatabase.ConnectTo())
            using (var transaction = connection.BeginTransaction(IsolationLevel.Snapshot))
            {
                downloadData = (await connection.QueryWithRetryAsync<DownloadCountData>(
                    _storedProcedureName, commandType: CommandType.StoredProcedure, transaction: transaction, commandTimeout: _defaultCommandTimeout)).ToList();
            }

            Trace.TraceInformation("Gathered {0} rows of data.", downloadData.Count);

            if (downloadData.Any())
            {
                SemanticVersion semanticVersion = null;

                // Group based on Package Id
                var grouped = downloadData.GroupBy(p => p.PackageId);
                var registrations = new JArray();
                foreach (var group in grouped)
                {
                    var details = new JArray();
                    details.Add(group.Key);
                    foreach (var gv in group)
                    {
                        // downloads.v1.json should only contain normalized versions - ignore others
                        if (SemanticVersion.TryParse(gv.PackageVersion, out semanticVersion)
                            && gv.PackageVersion == semanticVersion.ToNormalizedString())
                        {
                            var version = new JArray(gv.PackageVersion, gv.TotalDownloadCount);
                            details.Add(version);
                        }
                    }
                    registrations.Add(details);
                }

                var reportText = registrations.ToString(Formatting.None);

                foreach (var storageContainerTarget in Targets)
                {
                    try
                    {
                        var targetBlobContainer = await GetBlobContainer(storageContainerTarget);
                        var blob = targetBlobContainer.GetBlockBlobReference(ReportName);
                        Trace.TraceInformation("Writing report to {0}", blob.Uri.AbsoluteUri);
                        blob.Properties.ContentType = "application/json";
                        await blob.UploadTextAsync(reportText);
                        Trace.TraceInformation("Wrote report to {0}", blob.Uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error writing report to storage account {0}, container {1}. {2} {3}",
                            storageContainerTarget.StorageAccount.Credentials.AccountName,
                            storageContainerTarget.ContainerName, ex.Message, ex.StackTrace);
                    }
                }
            }
        }