コード例 #1
1
ファイル: DataFormatTest.cs プロジェクト: sonyarouje/Neo4jD
        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());
        }
コード例 #2
1
        public JObject SerializeMessage(Message message)
        {
            JObject messageObject = new JObject();

            messageObject.Add("jsonrpc", JToken.FromObject("2.0"));

            if (message.MessageType == MessageType.Request)
            {
                messageObject.Add("id", JToken.FromObject(message.Id));
                messageObject.Add("method", message.Method);
                messageObject.Add("params", message.Contents);
            }
            else if (message.MessageType == MessageType.Event)
            {
                messageObject.Add("method", message.Method);
                messageObject.Add("params", message.Contents);
            }
            else if (message.MessageType == MessageType.Response)
            {
                messageObject.Add("id", JToken.FromObject(message.Id));

                if (message.Error != null)
                {
                    // Write error
                    messageObject.Add("error", message.Error);
                }
                else
                {
                    // Write result
                    messageObject.Add("result", message.Contents);
                }
            }

            return messageObject;
        }
コード例 #3
1
ファイル: JsonExceptionConverter.cs プロジェクト: NSwag/NSwag
        /// <summary>Writes the JSON representation of the object.</summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var exception = value as Exception;
            if (exception != null)
            {
                var resolver = serializer.ContractResolver as DefaultContractResolver ?? _defaultContractResolver;

                var jObject = new JObject();
                jObject.Add(resolver.GetResolvedPropertyName("discriminator"), exception.GetType().Name);
                jObject.Add(resolver.GetResolvedPropertyName("Message"), exception.Message);
                jObject.Add(resolver.GetResolvedPropertyName("StackTrace"), _hideStackTrace ? "HIDDEN" : exception.StackTrace);
                jObject.Add(resolver.GetResolvedPropertyName("Source"), exception.Source);
                jObject.Add(resolver.GetResolvedPropertyName("InnerException"),
                    exception.InnerException != null ? JToken.FromObject(exception.InnerException, serializer) : null);

                foreach (var property in GetExceptionProperties(value.GetType()))
                {
                    var propertyValue = property.Key.GetValue(exception);
                    if (propertyValue != null)
                    {
                        jObject.AddFirst(new JProperty(resolver.GetResolvedPropertyName(property.Value),
                            JToken.FromObject(propertyValue, serializer)));
                    }
                }

                value = jObject;
            }

            serializer.Serialize(writer, value);
        }
コード例 #4
1
ファイル: JSON_IO_Extensions.cs プロジェクト: ipbi/sones
        public static JObject ToJSON(this QueryResult myQueryResult)
        {
            // root element...
            var _Query = new JObject();

            // query --------------------------------
            _Query.Add(new JProperty("query", myQueryResult.Query));

            // result -------------------------------
            _Query.Add(new JProperty("result", myQueryResult.ResultType.ToString()));

            // duration -----------------------------
            _Query.Add(new JProperty("duration", new JArray(myQueryResult.Duration, "ms")));

            // warnings -----------------------------
            _Query.Add(new JProperty("warnings", new JArray(
                from _Warning in myQueryResult.Warnings
                select new JObject(
                         new JProperty("code", _Warning.GetType().ToString()),
                         new JProperty("description", _Warning.ToString())
                       ))));

            // errors -------------------------------
            _Query.Add(new JProperty("errors", new JArray(
                from _Error in myQueryResult.Errors
                select new JObject(
                         new JProperty("code", _Error.GetType().ToString()),
                         new JProperty("description", _Error.ToString())
                       ))));

            // results ------------------------------
            _Query.Add(new JProperty("results", new JArray(GetJObjectsFromResult(myQueryResult.Vertices))));

            return _Query;
        }
コード例 #5
0
        private static void ConvertRecursively(IResource currentResource, JObject node, JsonSerializer serializer)
        {
            if (currentResource == null)
            {
                return;
            }

            var currentResourceType = currentResource.GetType();
            var readableProperties = GetReadablePropertyInfos(currentResourceType);

            var nonResourceProperties = readableProperties.Where(IsNeitherResourceOrReservedProperty).ToList();
            var resourceProperties = readableProperties.Where(IsResourceProperty).ToList();

            node.Add(ReservedPropertyNames.Relations, JObject.FromObject(currentResource.Relations, serializer));
            var embeddedResourceObject = new JObject();
            node.Add(ReservedPropertyNames.EmbeddedResources, embeddedResourceObject);

            foreach (var resourceProperty in resourceProperties)
            {                
                var embeddedResourceNodeValue = new JObject();

                ConvertRecursively((IResource)resourceProperty.GetValue(currentResource), embeddedResourceNodeValue, serializer);
                embeddedResourceObject.Add(ToCamelCase(resourceProperty.Name), embeddedResourceNodeValue);
            }

            if (IsCollectionResourceType(currentResourceType))
            {
                var currentResourceDynamic = (dynamic) currentResource;
                var jArray = new JArray();
                string name = "";
                foreach (IResource resourceItem in currentResourceDynamic.Items)
                {
                    var embeddedResourceNodeValue = new JObject();
                    ConvertRecursively(resourceItem, embeddedResourceNodeValue, serializer);
                    jArray.Add(embeddedResourceNodeValue);
                    name =  resourceItem.GetType().Name;
                }

                // Remove the "Resource" by convention.
                if (name.EndsWith("Resource"))
                {
                    name = name.Remove(name.LastIndexOf("Resource", StringComparison.Ordinal));
                }

                embeddedResourceObject.Add(ToCamelCase(name), jArray);
            }

            foreach (var nonResourceProperty in nonResourceProperties)
            {
                var value = nonResourceProperty.GetValue(currentResource);
                if (value != null && value.GetType().GetTypeInfo().IsClass && value.GetType() != typeof(string))
                {
                    node.Add(ToCamelCase(nonResourceProperty.Name), JToken.FromObject(value, serializer));
                }
                else
                {
                    node.Add(ToCamelCase(nonResourceProperty.Name), new JValue(value));
                }                
            }
        }
コード例 #6
0
ファイル: Model.cs プロジェクト: gbarnes12/skyengine
        public JObject serializeObject()
        {
            JObject obj = new JObject();

            obj.Add("Name", _name);
            obj.Add("Material", this._material.serializeObject());

            JObject multipartObj = new JObject();
            multipartObj.Add("UseMultipart", isMultipart);
            multipartObj.Add("Part", numberOfPart);
            multipartObj.Add("TotalParts", numberOfParts);
            obj.Add("Multipart", multipartObj);

            if(_meshes.Count != 0){
                JArray meshesNode = new JArray();

                for (int i = 0; i < _meshes.Count; i++)
                {
                    Mesh m = _meshes[i];
                    meshesNode.Add(m.serializeObject());
                }
                obj.Add("Meshes", meshesNode);

                return obj;
            }
            return null;
        }
コード例 #7
0
ファイル: Result.cs プロジェクト: prathapkora/TinCan.NET
        public override JObject ToJObject(TCAPIVersion version) {
            JObject result = new JObject();

            if (completion != null)
            {
                result.Add("completion", completion);
            }
            if (success != null)
            {
                result.Add("success", success);
            }
            if (response != null)
            {
                result.Add("response", response);
            }
            if (duration != null)
            {
                result.Add("duration", XmlConvert.ToString(duration));
            }
            if (score != null)
            {
                result.Add("score", score.ToJObject(version));
            }
            if (extensions != null)
            {
                result.Add("extensions", extensions.ToJObject(version));
            }

            return result;
        }
コード例 #8
0
        public bool Send(string userEmail, string sender, string body)
        {
            string appUrl = RoleEnvironment.GetConfigurationSettingValue("MobileServices.ApplicationUrl");
            string appKey = RoleEnvironment.GetConfigurationSettingValue("MobileServices.ApplicationKey");

            JObject json = new JObject();
            json.Add("userEmail", userEmail);
            json.Add("sender", sender);
            json.Add("body", body);

            var request = (HttpWebRequest)WebRequest.Create(appUrl + "api/sendpush");
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";
            request.Headers.Add("X-ZUMO-MASTER", appKey);

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json.ToString());
                streamWriter.Flush();
                streamWriter.Close();
            }

            var response = (HttpWebResponse)request.GetResponse();

            return response.StatusCode == HttpStatusCode.OK;
        }
コード例 #9
0
        public Newtonsoft.Json.Linq.JArray processer(string jsonStr)
        {
            //获取搜索到的分类号列表
            JArray mjsa = JArray.Parse(jsonStr);
            JObject mjosn = new JObject();
            mjosn = JObject.Parse(mjsa[0].ToString());
            string userID = mjosn["userID"].ToString();
            string kewWord = mjosn["keyWord"].ToString();
            //fatherCode
            string fatherCode = mjosn["fatherCode"].ToString();

            string sql = "select * from Dict_固定资产 where 名称 like '%" + kewWord + "%' and LEN(代码) =8 and 层级码 like '" + fatherCode + "%'  ";
            List<Model> list = base.queryBySql(sql, new Dict_固定资产RowMapper());
            JArray jsaa = new JArray();
            foreach (Model m in list)
            {
                JObject j = new JObject();

                j.Add("代码", ((Dict_固定资产Model)m).get代码());
                j.Add("名称", ((Dict_固定资产Model)m).get名称());
                j.Add("层级码", ((Dict_固定资产Model)m).get层级码());


                jsaa.Add(j);
            }

            return jsaa;
            
        }
コード例 #10
0
ファイル: userinfo2.aspx.cs プロジェクト: jinwmmail/RDFNew
 private void LoadData()
 {
     JObject jo = new JObject();
     jo.Add("BoxMargin", "0");
     jo.Add("BoxFlex", 1);
     UserInfoControl5.Properties = jo.ToString(Formatting.None);
 }
コード例 #11
0
ファイル: ApiUtil.cs プロジェクト: RSDT/JotiApiT
        public static async Task<string> Login()
        {

            Console.WriteLine("--- LOGIN ---");
            Console.Write("Username: "******"Password: "******"gebruiker", gebruiker);
            jsonObj.Add("ww", SHA1Util.SHA1HashStringForUTF8String(password));

            string result = await RequestUtil.Post(LinkBuilder.Build(new string[] { "login" }), jsonObj.ToString());
            string key = String.Empty;


            try
            {
                key = JObject.Parse(result)["SLEUTEL"].ToString();
                Logger.Log("ApiUtil", "Key aqquired: " + key, Logger.LogLevel.Info);
            } catch(Exception e)
            {
                Logger.Log("ApiUtil", result, Logger.LogLevel.Error);
            }
            return key;
        }
コード例 #12
0
        public ICollection<XbmcArtist> GetArtists(int start, int end)
        {
            this.client.LogMessage("XbmcAudioLibrary.GetArtists()");

            JObject args = new JObject();
            args.Add(new JProperty("fields", XbmcArtist.Fields));
            if (start >= 0)
            {
                args.Add(new JProperty("start", start));
            }
            if (end >= 0)
            {
                args.Add(new JProperty("end", end));
            }

            JObject query = this.client.Call("AudioLibrary.GetArtists", args) as JObject;
            if (query == null || query["artists"] == null)
            {
                this.client.LogErrorMessage("AudioLibrary.GetArtists(): Invalid response");

                return null;
            }

            List<XbmcArtist> artists = new List<XbmcArtist>();
            foreach (JObject item in (JArray)query["artists"])
            {
                artists.Add(XbmcArtist.FromJson(item));
            }

            return artists;
        }
コード例 #13
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);
        }
コード例 #14
0
        public override JObject ToJObject(TCAPIVersion version) {
            JObject result = new JObject();

            if (type != null)
            {
                result.Add("type", type.ToString());
            }
            if (moreInfo != null)
            {
                result.Add("moreInfo", moreInfo.ToString());
            }
            if (name != null && ! name.isEmpty())
            {
                result.Add("name", name.ToJObject(version));
            }
            if (description != null && ! description.isEmpty())
            {
                result.Add("description", description.ToJObject(version));
            }
            if (extensions != null && ! extensions.isEmpty())
            {
                result.Add("extensions", extensions.ToJObject(version));
            }

            return result;
        }
コード例 #15
0
ファイル: RESTApi_Test.cs プロジェクト: sonyarouje/Neo4jD
        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();
        }
コード例 #16
0
        private static byte[] GetGcmData(string userNameFromComment, IEnumerable<User> users, string message, Feeling feeling)
        {
            var jsonObject = new JObject();
            var arr = new JArray();
            users.Where(u => !string.IsNullOrWhiteSpace(u.Key)).ForEach(u => arr.Add(u.Key));
            if (!arr.Any())
                return null;

            jsonObject.Add("registration_ids", arr);
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            var data = new JObject
            {
                {"message", message},
                {"user", userNameFromComment},
                {"feeling", JsonConvert.SerializeObject(feeling.Id, Formatting.Indented, jsonSerializerSettings)}
            };

            jsonObject.Add("data", data);
            var postData = JsonConvert.SerializeObject(jsonObject);
            var byteArray = Encoding.UTF8.GetBytes(postData);
            return byteArray;
        }
コード例 #17
0
        public void testMsgContentAndExtras()
        {
            Message message = Message.content("msgContent");
            message.AddExtras("key1", "value1");
            message.AddExtras("key2", 222);
            message.AddExtras("key3", false);
            message.Check();

            JObject json = new JObject();
            json.Add("msg_content",JToken.FromObject("msgContent"));

            JObject extras = new JObject();
            extras.Add("key1", JToken.FromObject("value1"));
            extras.Add("key2", JToken.FromObject(222));
            extras.Add("key3", JToken.FromObject(false));

            json.Add("extras", extras);

            var jSetting = new JsonSerializerSettings();
            jSetting.DefaultValueHandling = DefaultValueHandling.Ignore;
            var jsonString = JsonConvert.SerializeObject(message, jSetting);
            var jsonObject = json.ToString(Formatting.None);
            var fromJson = JsonConvert.DeserializeObject<Message>(jsonObject);
            Assert.AreEqual(jsonObject, jsonString);
     }
コード例 #18
0
        public ICollection<XbmcJsonRpcMethod> Introspect(bool getPermissions, bool getDescriptions, bool filterByTransport)
        {
            this.client.LogMessage("XbmcJsonRpc.Introspect()");

            JObject args = new JObject();
            args.Add(new JProperty("getpermissions", getPermissions));
            args.Add(new JProperty("getDescriptions", getDescriptions));
            args.Add(new JProperty("filterbytransport", filterByTransport));

            JObject query = this.client.Call("JSONRPC.Introspect", args) as JObject;
            List<XbmcJsonRpcMethod> methods = new List<XbmcJsonRpcMethod>();

            if (query == null || query["commands"] == null)
            {
                this.client.LogErrorMessage("JSONRPC.Introspect: Invalid response");

                return methods;
            }

            foreach (JObject item in (JArray)query["commands"])
            {
                methods.Add(XbmcJsonRpcMethod.FromJson(item));
            }

            return methods;
        }
コード例 #19
0
ファイル: DocumentValue.cs プロジェクト: EBassie/Potato
        /// <summary>
        /// Converts this document into a base JObject
        /// </summary>
        /// <returns></returns>
        public JObject ToJObject() {
            JObject data = new JObject();

            foreach (Assignment assignment in this.Where(statement => statement is Assignment)) {
                Field field = assignment.FirstOrDefault(statement => statement is Field) as Field;
                Value value = assignment.FirstOrDefault(statement => statement is Value) as Value;

                if (field != null && value != null) {
                    DocumentValue document = value as DocumentValue;
                    CollectionValue collection = value as CollectionValue;

                    // If it's a sub document..
                    if (document != null) {
                        data.Add(new JProperty(field.Name, document.ToJObject()));
                    }
                    // If it's an array of values (no assignments)
                    else if (collection != null) {
                        data.Add(new JProperty(field.Name, collection.ToJArray()));
                    }
                    else {
                        data.Add(new JProperty(field.Name, value.ToObject()));
                    }
                }
            }

            return data;
        }
        public Newtonsoft.Json.Linq.JArray processer(string jsonStr)
        {
            String userID=null;
            String pTypeID=null;
             JArray jsa = JArray.Parse(jsonStr);
            JObject json = JObject.Parse(jsa[0].ToString());
            pTypeID = json["pTypeID"].ToString();
            userID = json["userID"].ToString();
          
		Dict_固定资产Dao dd=new Dict_固定资产Dao();
		
		//例如是3
	List<Model>	list=dd.getAllFatherTypeByID(pTypeID);
	JArray jsaa=new JArray();

	foreach(Model m in list){
		JObject j=new JObject();
		 
			j.Add("代码", ((Dict_固定资产Model)m).get代码());
			j.Add("名称", ((Dict_固定资产Model)m).get名称());
			j.Add("层级码",((Dict_固定资产Model)m).get层级码());
		 
		jsaa.Add(j);
	}
	
		return jsaa;
        }
コード例 #21
0
ファイル: Files.cs プロジェクト: Cocotus/Ember-MM-Newscraper
         /// <summary>
         /// Get the directories and files in the given directory
         /// </summary>
 public async Task<XBMCRPC.Files.GetDirectoryResponse> GetDirectory(string directory=null, XBMCRPC.Files.Media media=0, XBMCRPC.List.Fields.Files properties=null, XBMCRPC.List.Sort sort=null, XBMCRPC.List.Limits limits=null)
 {
     var jArgs = new JObject();
      if (directory != null)
      {
          var jpropdirectory = JToken.FromObject(directory, _client.Serializer);
          jArgs.Add(new JProperty("directory", jpropdirectory));
      }
      if (media != null)
      {
          var jpropmedia = JToken.FromObject(media, _client.Serializer);
          jArgs.Add(new JProperty("media", jpropmedia));
      }
      if (properties != null)
      {
          var jpropproperties = JToken.FromObject(properties, _client.Serializer);
          jArgs.Add(new JProperty("properties", jpropproperties));
      }
      if (sort != null)
      {
          var jpropsort = JToken.FromObject(sort, _client.Serializer);
          jArgs.Add(new JProperty("sort", jpropsort));
      }
      if (limits != null)
      {
          var jproplimits = JToken.FromObject(limits, _client.Serializer);
          jArgs.Add(new JProperty("limits", jproplimits));
      }
     return await _client.GetData<XBMCRPC.Files.GetDirectoryResponse>("Files.GetDirectory", jArgs);
 }
コード例 #22
0
        static void Main(string[] args)
        {
            var jGcmData = new JObject();
            var jData = new JObject();

            jData.Add("message", MESSAGE);
            jGcmData.Add("to", "/topics/global");
            jGcmData.Add("data", jData);

            var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.TryAddWithoutValidation(
                        "Authorization", "key=" + API_KEY);

                    Task.WaitAll(client.PostAsync(url,
                        new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                            .ContinueWith(response =>
                            {
                                Console.WriteLine(response);
                                Console.WriteLine("Message sent: check the client device notification tray.");
                            }));
                }
            } 
            catch (Exception e)
            {
                Console.WriteLine("Unable to send GCM message:");
                Console.Error.WriteLine(e.StackTrace);
            }
        }
コード例 #23
0
ファイル: JsonApiProvider.cs プロジェクト: niel/NzbDrone
        public List<ActivePlayer> GetActivePlayers(XbmcSettings settings)
        {
            try
            {
                var postJson = new JObject();
                postJson.Add(new JProperty("jsonrpc", "2.0"));
                postJson.Add(new JProperty("method", "Player.GetActivePlayers"));
                postJson.Add(new JProperty("id", 10));

                var response = _httpProvider.PostCommand(settings.Address, settings.Username, settings.Password, postJson.ToString());

                if (CheckForError(response))
                    return new List<ActivePlayer>();

                var result = Json.Deserialize<ActivePlayersEdenResult>(response);

                return result.Result;
            }

            catch (Exception ex)
            {
                _logger.DebugException(ex.Message, ex);
            }

            return new List<ActivePlayer>();
        }
コード例 #24
0
        /// <summary>
        /// Populates <paramref name="target"/> with static and <paramref name="source"/> values
        /// as defined by <paramref name="fieldMap"/>.
        /// </summary>
        /// <param name="source">The application from which to get field values.</param>
        /// <param name="fieldMap">A definition of field mappings.</param>
        /// <param name="target">The target object to populate with mapped key/values.</param>
        internal void Map(Application source, MappedFieldList fieldMap, JObject target)
        {
            foreach (MappedField map in fieldMap)
            {
                switch (map.MapType)
                {
                    case MapType.Value:
                    case MapType.PrivateValue:
                        target.Add(map.Target, map.Source);
                        break;

                    case MapType.Field:
                        object tokenValue = source.GetTokenValue(map.Source);
                        if (tokenValue == null)
                        {
                            target.Add(map.Target, string.Empty);
                        }
                        else if (tokenValue is IEnumerable<object>)
                        {
                            target.Add(map.Target, JArray.FromObject(tokenValue));
                        }
                        else
                        {
                            target.Add(map.Target, tokenValue.ToString());
                        }

                        break;

                    default:
                        throw new InvalidOperationException(string.Format(ExceptionMessages.InvalidMapType, map.MapType));
                }
            }
        }
コード例 #25
0
ファイル: Client.cs プロジェクト: shlee322/Netronics
 // 클라이언트가 접속시 호출
 public void Connected(IReceiveContext channel)
 {
     JObject o = new JObject();
     o.Add("name", "test");
     o.Add("value", i++);
     channel.GetChannel().SendMessage(o);
 }
コード例 #26
0
        public void addToApplicationSearch(Keymap keymap, string search)
        {
            if (this.isInApplicationSearch(keymap))
            {
                return;
            }

            JToken level1 = this.jsonObj.GetValue("Applications");
            if (level1 == null)
            {
                this.jsonObj.Add("Applications", new JArray());
            }
            level1 = this.jsonObj.GetValue("Applications");
            JArray array = (JArray)level1;

            JObject newObj = new JObject();
            newObj.Add("Search", search);
            newObj.Add("Keymap", keymap.Filename);
            array.Add(newObj);

            this.jsonObj.Remove("Applications");
            this.jsonObj.Add("Applications", array);

            save();
        }
コード例 #27
0
        public ActionResult Index(string errorMessage)
        {
            var client = new CouchClient("dannylane.iriscouch.com", 6984, "dannylane", "adminpass", true, AuthenticationType.Cookie);
            var udb = client.GetDatabase("testing");

            JObject jObject = new JObject();

            jObject.Add("DateTime", DateTime.UtcNow);
            jObject.Add("UserHostAddress", Request.UserHostAddress);
            jObject.Add("UserHostName", Request.UserHostName);
          //  jObject.Add("UserLanguages", Request.UserLanguages.ToString());
            
            foreach (var param in Request.QueryString.AllKeys)
            {
                jObject.Add(param, Request.QueryString[param]);
            }

            foreach (var param in Request.Headers.AllKeys)
            {
                jObject.Add(param, Request.Headers[param]);
            }

            var info = new LoveSeat.Document(jObject);
            
            udb.SaveDocument(info);
            return File("favicon.ico","image");
        }
コード例 #28
0
        public ActionResult Import(string savedFileName)
        {
            var jo = new JObject();
            string result;

            try
            {
                var fileName = string.Concat(Server.MapPath(fileSavedPath), "/", savedFileName);

                var importZipCodes = new List<TaiwanZipCode>();

                var helper = new ImportDataHelper();
                var checkResult = helper.CheckImportData(fileName, importZipCodes);

                jo.Add("Result", checkResult.Success);
                jo.Add("Msg", checkResult.Success ? string.Empty : checkResult.ErrorMessage);

                if (checkResult.Success)
                {
                    //儲存匯入的資料
                    helper.SaveImportData(importZipCodes);
                }
                result = JsonConvert.SerializeObject(jo);
            }
            catch (Exception ex)
            {
                throw;
            }
            return Content(result, "application/json");
        }
コード例 #29
0
        public bool CreditAccount(string PaydunyaAccount, double Amount)
        {
            bool result = false;
            JObject payload = new JObject();

            payload.Add("account_alias", PaydunyaAccount);
            payload.Add("amount", Amount);
            string jsonData = JsonConvert.SerializeObject(payload);

            JObject JsonResult = utility.HttpPostJson(setup.GetDirectPayCreditUrl(), jsonData);

            ResponseCode = JsonResult["response_code"].ToString();
            if (ResponseCode == "00")
            {
                Status = SUCCESS;
                ResponseText = JsonResult["response_text"].ToString();
                Description = JsonResult["description"].ToString();
                TransactionId = JsonResult["transaction_id"].ToString();
                result = true;
            }
            else
            {
                ResponseText = JsonResult["response_text"].ToString();
                Status = FAIL;
            }
            return result;
        }
コード例 #30
0
ファイル: Packet.cs プロジェクト: shlee322/Netronics
 public static void SendMessage(this IChannel channel, string type, JToken args)
 {
     var packet = new JObject();
     packet.Add("type", type);
     packet.Add("args", args);
     channel.SendMessage(packet);
 }
コード例 #31
0
        internal string SendBroadcast(string message)
        {
            JObject jGcmData = new JObject();
            JObject jData = new JObject();

            jData.Add(new JProperty("message", message));
            jGcmData.Add(new JProperty("to", "/topics/vertretungsplan"));
            jGcmData.Add("data", jData);

            UTF8Encoding encoding = new UTF8Encoding();
            byte[] data = encoding.GetBytes(jGcmData.ToString());

            HttpWebRequest messageRequest = WebRequest.CreateHttp("https://android.googleapis.com/gcm/send");
            messageRequest.ContentType = "application/json";
            messageRequest.Headers.Add(HttpRequestHeader.Authorization, "key=" + API_KEY);
            messageRequest.Method = "POST";

            Stream requestStream = messageRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            WebResponse response = messageRequest.GetResponse();
            StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            return responseReader.ReadToEnd();
        } 
コード例 #32
0
        public async void EnvioDatos(string TK, Recepcion objRecepcion)
        {
            try
            {
                string URL_RECEPCION = "https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/";

                HttpClient http = new HttpClient();

                Newtonsoft.Json.Linq.JObject JsonObject = new Newtonsoft.Json.Linq.JObject();
                JsonObject.Add(new JProperty("clave", objRecepcion.clave));
                JsonObject.Add(new JProperty("fecha", objRecepcion.fecha));
                JsonObject.Add(new JProperty("emisor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.emisor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.emisor.numeroIdentificacion))));
                JsonObject.Add(new JProperty("receptor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.receptor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.receptor.numeroIdentificacion))));
                JsonObject.Add(new JProperty("comprobanteXml", objRecepcion.comprobanteXml));

                jsonEnvio = JsonObject.ToString();

                StringContent oString = new StringContent(JsonObject.ToString());

                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));

                HttpResponseMessage response = http.PostAsync((URL_RECEPCION + "recepcion"), oString).Result;
                string res = await response.Content.ReadAsStringAsync();

                object Localizacion = response.StatusCode;
                // mensajeRespuesta = Localizacion

                http = new HttpClient();
                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));
                response = http.GetAsync((URL_RECEPCION + ("recepcion/" + objRecepcion.clave))).Result;
                res      = await response.Content.ReadAsStringAsync();

                jsonRespuesta = res.ToString();

                RespuestaHacienda RH = Newtonsoft.Json.JsonConvert.DeserializeObject <RespuestaHacienda>(res);

                if ((RH.respuesta_xml != ""))
                {
                    xmlRespuesta = Funciones.DecodeBase64ToXML(RH.respuesta_xml);
                }

                try { }
                catch { }

                estadoFactura = RH.ind_estado;
                statusCode    = response.StatusCode.ToString();

                mensajeRespuesta = ("Confirmación: " + (statusCode + "\r\n"));
                mensajeRespuesta = (mensajeRespuesta + ("Estado: " + estadoFactura));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #33
0
ファイル: Program.cs プロジェクト: Oryhara/Gvoice
            public void uploadTestRailResult(int caseID, int result, string comment)
            {
                var    requestData = new Newtonsoft.Json.Linq.JObject();
                string uri         = "add_result/" + caseID.ToString();

                requestData.Add("status_id", result);
                requestData.Add("comment", comment);
                TRClient.SendPost(uri, requestData);
            }
コード例 #34
0
        public static async void unMark(Object data)
        {
            ResourceData resourceData = data as ResourceData;

            if (resourceData != null)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject();
                jObject.Add("sjh", Rigel.UserID);
                jObject.Add("lb", App.ResourceType.ToString());
                jObject.Add("tmid", resourceData.ID.ToString());
                await RequestHandle.delWdsc(jObject);
            }
        }
コード例 #35
0
        public static async void store(Object data)
        {
            ResourceData resourceData = data as ResourceData;

            if (resourceData != null)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject();
                jObject.Add("sjh", Rigel.UserID);
                jObject.Add("lb", App.ResourceType.ToString());
                jObject.Add("tmid", resourceData.ID.ToString());
                jObject.Add("scsj", DateTime.Now.Date.ToString("yyyyMMddHHmmss"));
                await RequestHandle.Wdsc(jObject);
            }
        }
コード例 #36
0
    static int Add(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JObject), typeof(object)))
            {
                Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)ToLua.ToObject(L, 1);
                object arg0 = ToLua.ToVarObject(L, 2);
                obj.Add(arg0);
                return 0;
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JObject), typeof(string), typeof(Newtonsoft.Json.Linq.JToken)))
            {
                Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)ToLua.ToObject(L, 1);
                string arg0 = ToLua.ToString(L, 2);
                Newtonsoft.Json.Linq.JToken arg1 = (Newtonsoft.Json.Linq.JToken)ToLua.ToObject(L, 3);
                obj.Add(arg0, arg1);
                return 0;
            }
            else
            {
                return LuaDLL.luaL_throw(L, "invalid arguments to method: Newtonsoft.Json.Linq.JObject.Add");
            }
        }
        catch(Exception e)
        {
            return LuaDLL.toluaL_exception(L, e);
        }
    }
コード例 #37
0
    static int Add(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2)
            {
                Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)ToLua.CheckObject <Newtonsoft.Json.Linq.JObject>(L, 1);
                object arg0 = ToLua.ToVarObject(L, 2);
                obj.Add(arg0);
                return(0);
            }
            else if (count == 3)
            {
                Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)ToLua.CheckObject <Newtonsoft.Json.Linq.JObject>(L, 1);
                string arg0 = ToLua.CheckString(L, 2);
                Newtonsoft.Json.Linq.JToken arg1 = (Newtonsoft.Json.Linq.JToken)ToLua.CheckObject <Newtonsoft.Json.Linq.JToken>(L, 3);
                obj.Add(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Newtonsoft.Json.Linq.JObject.Add"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
コード例 #38
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);
        }
コード例 #39
0
        public HttpResponseMessage Set(Guid userId, [FromBody] string value)
        {
            try
            {
                Newtonsoft.Json.Linq.JObject data = Newtonsoft.Json.Linq.JObject.Parse(value);
                data.Add("userUpdateId", userId.ToString());
                IFolderService      servFolder = Utility.MyUnityHelper.UnityHelper.Resolve <IFolderService>();
                TakeDocModel.Folder folder     = servFolder.Create(data);

                var json = new
                {
                    id           = folder.FolderId,
                    folderId     = folder.FolderId,
                    title        = folder.FolderLabel,
                    start        = folder.FolderDateStart,
                    end          = folder.FolderDateEnd,
                    allDay       = false,
                    entityId     = folder.EntityId,
                    ownerId      = folder.FolderOwnerId,
                    folderTypeId = folder.FolderTypeId,
                };

                return(Request.CreateResponse(json));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
コード例 #40
0
ファイル: B2bApi.cs プロジェクト: Fyyk-Whua/B2bApiInterface
        /// <summary>
        /// Post方式提交数据,返回网页的源代码
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="param">请求的参数集合</param>
        /// <returns>远程资源的响应结果</returns>
        private string SendPost(Log4netUtil.LogAppendToForms logAppendToForms,
                                Model.JobEntity jobInfo,
                                string url, string postData)
        {
            string logMessage = string.Empty;
            string result     = string.Empty;

            byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (url.Substring(0, 8) == "https://")
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }
                request.ContentType   = "application/json";// "application/x-www-form-urlencoded";
                request.Referer       = url;
                request.Accept        = "*/*";
                request.Timeout       = 30 * 1000;
                request.UserAgent     = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.Method        = "POST";
                request.ContentLength = byteData.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteData, 0, byteData.Length);
                stream.Flush();
                stream.Close();
                HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
                Stream          backStream = response.GetResponseStream();
                StreamReader    sr         = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
                result = sr.ReadToEnd();
                sr.Close();
                backStream.Close();
                response.Close();
                request.Abort();
            }
            catch (Exception ex)
            {
                logMessage = string.Format("【{0}_{1}】 SendPost b2bApi接口失败 失败原因:{2}", jobInfo.JobCode, jobInfo.JobName, ex.Message);
                Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject();
                jObject.Add("code", 999);
                jObject.Add("msg", ex.Message);
                jObject.Add("data", string.Empty);
                result = Util.NewtonsoftCommon.SerializeObjToJson(jObject);
            }
            return(result);
        }
コード例 #41
0
ファイル: TestOptiML.cs プロジェクト: mmerce/bigml-csharp
        public async Task CreateOptiMLFromRemoteSource()
        {
            Client c = new Client(userName, apiKey);

            Project.Arguments pArgs = new Project.Arguments();
            pArgs.Add("name", "Test Project");
            Project p1 = await c.CreateProject(pArgs);

            Project p2 = await c.CreateProject(pArgs);

            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "https://static.bigml.com/csv/iris.csv");
            args.Add("name", "C# tests - Iris");
            // The project can be added as a regular parameter in the creation
            args.Add("project", p1.Resource);

            Source s = await c.CreateSource(args);

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

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

            // Update the project
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            changes.Add("project", p2.Resource);
            s = await c.Update <Source>(s.Resource, changes);

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


            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);

            OptiML.Arguments argsOM = new OptiML.Arguments();
            argsOM.Add("dataset", ds.Resource);
            argsOM.Add("name", "C# tests - TestOptiML");
            argsOM.Add("max_training_time", 100);
            OptiML om = await c.CreateOptiML(argsOM);

            om = await c.Wait <OptiML>(om.Resource);

            // This step can take a bit
            Assert.AreNotEqual(om.StatusMessage.StatusCode, Code.Faulty);

            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(om);

            await c.Delete(p1);

            await c.Delete(p2);
        }
コード例 #42
0
ファイル: Program.cs プロジェクト: xiaopangzi313/QTranser
        private static void dd()
        {
            //Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject {{"Entered", DateTime.Now}};
            Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject();
            jsonObject.Add("Entered", DateTime.Now);
            dynamic album = jsonObject;

            album.AlbumName = "非主流歌曲";

            foreach (var item in jsonObject)  //循环输出动态的值  JObject(基类为JContainer、JObject和JArray)是一个集合,实现了IEnumerable接口,因此你还可以轻松地在运行时循环访问
            {
                Console.WriteLine(item.Key + "的值为:" + item.Value.ToString());
            }
        }
コード例 #43
0
        public void MergeTwoResponses()
        {
            var response1 = LoadJson <Dns.DTO.QueryComposer.QueryComposerResponseDTO>("Lpp.Dns.Api.Tests.Requests.Samples.DM1-response.json");
            var response2 = LoadJson <Dns.DTO.QueryComposer.QueryComposerResponseDTO>("Lpp.Dns.Api.Tests.Requests.Samples.DM2-response.json");

            IEnumerable <Dictionary <string, object> > r1 = response1.Queries.SelectMany(q => q.Results).First();

            Console.WriteLine("Result 1 count:" + r1.Count());
            IEnumerable <Dictionary <string, object> > r2 = response2.Queries.SelectMany(q => q.Results).First();

            Console.WriteLine("Result 2 count:" + r2.Count());
            Console.WriteLine("Total count:" + (r1.Count() + r2.Count()));

            IEnumerable <Dictionary <string, object> > combined = r1.Select(d => { d.Add("DataMart", "DM1"); return(d); }).Concat(r2.Select(d => { d.Add("DataMart", "DM2"); return(d); })).ToArray();

            Dns.DTO.QueryComposer.QueryComposerResponseDTO combinedResponse = new DTO.QueryComposer.QueryComposerResponseDTO {
                Header = new DTO.QueryComposer.QueryComposerResponseHeaderDTO {
                    ID          = Guid.NewGuid(),
                    RequestID   = Guid.Empty,
                    QueryingEnd = DateTimeOffset.UtcNow
                },
                Queries = new[] { new DTO.QueryComposer.QueryComposerResponseQueryResultDTO {
                                      ID         = Guid.NewGuid(),
                                      QueryStart = DateTimeOffset.UtcNow,
                                      QueryEnd   = DateTimeOffset.UtcNow,
                                      Results    = new [] { combined }
                                  } }
            };

            string mergedSerialized = Newtonsoft.Json.JsonConvert.SerializeObject(combinedResponse, Newtonsoft.Json.Formatting.None);

            System.IO.File.WriteAllText("merged-response.json", mergedSerialized);

            Newtonsoft.Json.Linq.JObject jobj = new Newtonsoft.Json.Linq.JObject();
            jobj.Add("prop1", new Newtonsoft.Json.Linq.JValue("23"));



            /**
             * Test Name:	MergeTwoResponses
             * Test Outcome:	Passed
             * Result StandardOutput:
             * Lpp.Dns.Api.Tests.Requests.Samples.DM1-response.json
             * Lpp.Dns.Api.Tests.Requests.Samples.DM2-response.json
             * Lpp.Dns.Api.Tests.Requests.Samples.request.json
             *
             *
             * */
        }
コード例 #44
0
        static private void BuildTree(ItemTree root, Newtonsoft.Json.Linq.JObject rootObject, NameToJsonObject mapObjects)
        {
            if (root.type == "root" || root.type == "menu")
            {
                if (root.type == "menu")
                {
                    JObject childObject = new JObject();
                    rootObject.Add(root.name, childObject);
                    rootObject = childObject;
                }


                foreach (ItemTree subitem in root.subitems)
                {
                    BuildTree(subitem, rootObject, mapObjects);
                }
            }
            else
            {
                JProperty prop = new JProperty(root.name, null);
                rootObject.Add(prop);
                mapObjects.Add(root.FullName, prop);
            }
        }
コード例 #45
0
ファイル: TestDeepnets.cs プロジェクト: mmerce/bigml-csharp
        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);
        }
コード例 #46
0
        public HttpResponseMessage Put(Guid userId, [FromBody] string value)
        {
            try
            {
                Newtonsoft.Json.Linq.JObject data = Newtonsoft.Json.Linq.JObject.Parse(value);
                data.Add("userUpdateId", userId.ToString());
                IFolderService servFolder = Utility.MyUnityHelper.UnityHelper.Resolve <IFolderService>();
                servFolder.Update(data);

                return(Request.CreateResponse("OK"));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
コード例 #47
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);
        }
コード例 #48
0
ファイル: JsonFilter.cs プロジェクト: yonglehou/TimberWinR
        private void AddTags(Newtonsoft.Json.Linq.JObject json)
        {
            if (AddTag != null && AddTag.Length > 0)
            {
                for (int i = 0; i < AddTag.Length; i++)
                {
                    string value = ExpandField(AddTag[i], json);

                    JToken tags = json["tags"];
                    if (tags == null)
                    {
                        json.Add("tags", new JArray(value));
                    }
                    else
                    {
                        JArray a = tags as JArray;
                        a.Add(value);
                    }
                }
            }
        }
コード例 #49
0
ファイル: DynamicJson.cs プロジェクト: liuxiqin/IFramework
        public override bool TrySetMember(SetMemberBinder binder, object val)
        {
            bool ret = true;

            try
            {
                var property = _json.Property(binder.Name);
                if (property != null)
                {
                    property.Value = JToken.FromObject(val);
                }
                else
                {
                    _json.Add(binder.Name, new JObject(val));
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            return(ret);
        }
コード例 #50
0
        //
        public void EnvioDatos(string TK, Recepcion objRecepcion)
        {
            try
            {
                HttpClient http = new HttpClient();
                Newtonsoft.Json.Linq.JObject JsonObject = new Newtonsoft.Json.Linq.JObject();
                JsonObject.Add(new JProperty("clave", objRecepcion.clave));
                JsonObject.Add(new JProperty("fecha", objRecepcion.fecha));
                JsonObject.Add(new JProperty("emisor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.emisor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.emisor.numeroIdentificacion))));
                JsonObject.Add(new JProperty("receptor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.receptor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.receptor.numeroIdentificacion))));

                JsonObject.Add(new JProperty("consecutivoReceptor", objRecepcion.consecutivoReceptor));

                JsonObject.Add(new JProperty("comprobanteXml", objRecepcion.comprobanteXml));

                jsonEnvio = JsonObject.ToString();

                StringContent oString = new StringContent(JsonObject.ToString());

                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));

                HttpResponseMessage response = http.PostAsync((URL_RECEPCION + "recepcion"), oString).Result;
                if (response.StatusCode.ToString() == "ServiceUnavailable" || response.StatusCode.ToString() == "BadGateway")
                {
                    mensajeRespuesta = "Servidor de Hacienda caído";
                }
                else
                {
                    Thread.Sleep(5000);//Tiempo de 3 segundos para esperar aprobacion o rechazo de hacienda
                    string consultaClave = objRecepcion.clave + "-" + objRecepcion.consecutivoReceptor;
                    ConsultaEstatus(TK, consultaClave);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #51
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));
        }
コード例 #52
0
 /// <summary>
 /// ConvertJArrayToDataTable
 /// </summary>
 /// <param name="logAppendToForms"></param>
 /// <param name="jobInfo"></param>
 /// <param name="dataArr"></param>
 /// <returns></returns>
 public static System.Data.DataTable ConvertJArrayToDataTable(Log4netUtil.LogAppendToForms logAppendToForms,
                                                              Model.JobEntity jobInfo, JArray dataArr)
 {
     if (dataArr == null || dataArr.Count <= 0)
     {
         string logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败!失败原因:JArray为空 ", jobInfo.JobCode, jobInfo.JobName);
         Newtonsoft.Json.Linq.JObject resultJObject = new Newtonsoft.Json.Linq.JObject();
         resultJObject.Add("code", 999);
         resultJObject.Add("msg", logMessage);
         resultJObject.Add("data", dataArr.ToString());
         logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败! ", jobInfo.JobCode, jobInfo.JobName);
         Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
         return(null);
     }
     System.Data.DataTable resultDt = new System.Data.DataTable();
     try
     {
         var           colnames    = ((JObject)(dataArr.First)).Properties();
         List <string> columnNames = new List <string>();
         if (colnames == null || colnames.Count() <= 0)
         {
             string logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败!失败原因:JArray Colnames为空 ", jobInfo.JobCode, jobInfo.JobName);
             Newtonsoft.Json.Linq.JObject resultJObject = new Newtonsoft.Json.Linq.JObject();
             resultJObject.Add("code", 999);
             resultJObject.Add("msg", logMessage);
             resultJObject.Add("data", dataArr.ToString());
             logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败! ", jobInfo.JobCode, jobInfo.JobName);
             Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
             return(null);
         }
         foreach (var item in colnames)
         {
             if (!columnNames.Contains(item.Name))
             {
                 columnNames.Add(item.Name);
             }
             resultDt.Columns.Add(item.Name, typeof(string));
         }
         foreach (JObject data in dataArr)
         {
             JObject             jo  = JObject.Parse(data.ToString());
             System.Data.DataRow row = resultDt.NewRow();
             foreach (var columnName in columnNames)
             {
                 if (jo.Property(columnName) == null)
                 {
                     data.Add(columnName, "");
                     row[columnName] = data[columnName].ToString();
                 }
                 else
                 {
                     row[columnName] = data[columnName].ToString();
                 }
             }
             resultDt.Rows.Add(row);
         }
         return(resultDt);
     }
     catch (Exception ex)
     {
         string logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败!失败原因:{2} ", jobInfo.JobCode, jobInfo.JobName, ex.Message);
         Newtonsoft.Json.Linq.JObject resultJObject = new Newtonsoft.Json.Linq.JObject();
         resultJObject.Add("code", 999);
         resultJObject.Add("msg", logMessage);
         resultJObject.Add("data", dataArr.ToString());
         logMessage = string.Format("【{0}_{1}】 ConvertJArrayToDataTable转换失败! ", jobInfo.JobCode, jobInfo.JobName);
         Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
         return(null);
     }
 }
コード例 #53
0
        /// <summary>
        /// 用户账户验证的后台端
        /// </summary>
        private void ThreadCheckAccount()
        {
            //定义委托
            Action <string> message_show = delegate(string message)
            {
                label_status.Text = message;
            };
            Action start_update = delegate
            {
                //需要该exe支持,否则将无法是实现自动版本控制
                string update_file_name = Application.StartupPath + @"\软件自动更新.exe";
                try
                {
                    System.Diagnostics.Process.Start(update_file_name);
                }
                catch
                {
                    MessageBox.Show("更新程序启动失败,请检查文件是否丢失,联系管理员获取。");
                }
            };
            Action thread_finish = delegate
            {
                UISettings(true);
            };

            //延时
            Thread.Sleep(200);

            //请求指令头数据,该数据需要更具实际情况更改
            OperateResultString result = UserClient.Net_simplify_client.ReadFromServer(CommonLibrary.CommonHeadCode.SimplifyHeadCode.维护检查);

            if (result.IsSuccess)
            {
                //例如返回结果为1说明允许登录,0则说明服务器处于维护中,并将信息显示
                if (result.Content != "1")
                {
                    if (IsHandleCreated)
                    {
                        Invoke(message_show, result.Content.Substring(1));
                    }
                    if (IsHandleCreated)
                    {
                        Invoke(thread_finish);
                    }
                    return;
                }
            }
            else
            {
                //访问失败
                if (IsHandleCreated)
                {
                    Invoke(message_show, result.Message);
                }
                if (IsHandleCreated)
                {
                    Invoke(thread_finish);
                }
                return;
            }

            //版本验证
            if (IsHandleCreated)
            {
                Invoke(message_show, "正在验证版本...");
            }
            else
            {
                return;
            }

            //延时
            Thread.Sleep(200);

            result = UserClient.Net_simplify_client.ReadFromServer(CommonLibrary.CommonHeadCode.SimplifyHeadCode.更新检查);
            if (result.IsSuccess)
            {
                //服务器应该返回服务器的版本号
                BasicFramework.SystemVersion sv = new BasicFramework.SystemVersion(result.Content);
                if (UserClient.CurrentVersion != sv)
                {
                    //保存新版本信息
                    UserClient.JsonSettings.IsNewVersionRunning = true;
                    UserClient.JsonSettings.SaveSettings();
                    //和当前系统版本号不一致,启动更新
                    if (IsHandleCreated)
                    {
                        Invoke(start_update);
                    }
                    return;
                }
            }
            else
            {
                //访问失败
                if (IsHandleCreated)
                {
                    Invoke(message_show, result.Message);
                }
                if (IsHandleCreated)
                {
                    Invoke(thread_finish);
                }
                return;
            }

            //检查账户
            if (IsHandleCreated)
            {
                Invoke(message_show, "正在检查账户...");
            }
            else
            {
                return;
            }

            //延时
            Thread.Sleep(200);

            //===================================================================================
            //   根据实际情况校验,选择数据库校验或是将用户名密码发至服务器校验
            //   以下展示了服务器校验的方法,如您需要数据库校验,请删除下面并改成SQL访问验证的方式

            //包装数据
            Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject();
            json.Add(BasicFramework.UserAccount.UserNameText, new Newtonsoft.Json.Linq.JValue(textBox_userName.Text));
            json.Add(BasicFramework.UserAccount.PasswordText, new Newtonsoft.Json.Linq.JValue(textBox_password.Text));

            result = UserClient.Net_simplify_client.ReadFromServer(CommonLibrary.CommonHeadCode.SimplifyHeadCode.账户检查 + json.ToString());
            if (result.IsSuccess)
            {
                //服务器应该返回账户的信息
                BasicFramework.UserAccount account = JObject.Parse(result.Content).ToObject <BasicFramework.UserAccount>();
                if (!account.LoginEnable)
                {
                    //不允许登录
                    if (IsHandleCreated)
                    {
                        Invoke(message_show, account.ForbidMessage);
                    }
                    if (IsHandleCreated)
                    {
                        Invoke(thread_finish);
                    }
                    return;
                }
                UserClient.UserAccount = account;
            }
            else
            {
                //访问失败
                if (IsHandleCreated)
                {
                    Invoke(message_show, result.Message);
                }
                if (IsHandleCreated)
                {
                    Invoke(thread_finish);
                }
                return;
            }

            //登录成功,进行保存用户名称和密码
            UserClient.JsonSettings.LoginName = textBox_userName.Text;
            UserClient.JsonSettings.Password  = checkBox_remeber.Checked ? textBox_password.Text : "";
            UserClient.JsonSettings.SaveSettings();


            //================================================================================
            //验证结束后,根据需要是否下载服务器的数据,或是等到进入主窗口下载也可以
            //如果有参数决定主窗口的显示方式,那么必要在下面向服务器请求数据
            //以下展示了初始化参数的功能
            if (IsHandleCreated)
            {
                Invoke(message_show, "正在下载参数...");
            }
            else
            {
                return;
            }

            //延时
            Thread.Sleep(200);


            result = UserClient.Net_simplify_client.ReadFromServer(CommonLibrary.CommonHeadCode.SimplifyHeadCode.参数下载);
            if (result.IsSuccess)
            {
                //服务器返回初始化的数据,此处进行数据的提取,有可能包含了多个数据
                json = Newtonsoft.Json.Linq.JObject.Parse(result.Content);
                //例如公告数据
                UserClient.Announcement = BasicFramework.SoftBasic.GetValueFromJsonObject(json, nameof(UserClient.Announcement), "");
            }
            else
            {
                //访问失败
                if (IsHandleCreated)
                {
                    Invoke(message_show, result.Message);
                }
                if (IsHandleCreated)
                {
                    Invoke(thread_finish);
                }
                return;
            }

            //启动主窗口
            if (IsHandleCreated)
            {
                Invoke(new Action(() =>
                {
                    DialogResult = DialogResult.OK;
                    return;
                }));
            }
        }
コード例 #54
0
        public async Task <String> EnvioDatos(string TK, Recepcion objRecepcion)
        {
            try
            {
                String URL_RECEPCION = URL;



                HttpClient http = new HttpClient();

                Newtonsoft.Json.Linq.JObject JsonObject = new Newtonsoft.Json.Linq.JObject();
                JsonObject.Add(new Newtonsoft.Json.Linq.JProperty("clave", objRecepcion.clave));
                JsonObject.Add(new JProperty("fecha", objRecepcion.fecha));
                JsonObject.Add(new JProperty("emisor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.emisor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.emisor.numeroIdentificacion.Trim()))));

                if (objRecepcion.receptor.sinReceptor == false)
                {
                    JsonObject.Add(new JProperty("receptor",
                                                 new JObject(new JProperty("tipoIdentificacion", objRecepcion.receptor.TipoIdentificacion),
                                                             new JProperty("numeroIdentificacion", objRecepcion.receptor.numeroIdentificacion))));
                }

                JsonObject.Add(new JProperty("comprobanteXml", objRecepcion.comprobanteXml));

                jsonEnvio = JsonObject.ToString();

                StringContent oString = new StringContent(JsonObject.ToString());

                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));

                HttpResponseMessage response = http.PostAsync((URL_RECEPCION + "recepcion"), oString).Result;
                string res = await response.Content.ReadAsStringAsync();

                object Localizacion = response.StatusCode;
                // mensajeRespuesta = Localizacion
                estadoEnvio = response.StatusCode.ToString();


                //http = new HttpClient();
                //http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));
                //response = http.GetAsync((URL_RECEPCION + ("recepcion/" + objRecepcion.clave))).Result;
                //res = await response.Content.ReadAsStringAsync();

                //jsonRespuesta = res.ToString();

                //RespuestaHacienda RH = Newtonsoft.Json.JsonConvert.DeserializeObject<RespuestaHacienda>(res);
                //if (RH !=null)
                //{
                //    existeRespuesta = true;
                //    if ((RH.respuesta_xml != null ))
                //    {
                //        xmlRespuesta = Funciones.DecodeBase64ToXML(RH.respuesta_xml);
                //    }
                //    estadoFactura = RH.ind_estado;

                //}
                //else
                //{

                //    existeRespuesta = false;
                //}

                //mensajeRespuesta = estadoFactura;
                statusCode = response.StatusCode.ToString();
                return(statusCode);
            }
            catch (Exception ex)
            {
                clsEvento evento = new clsEvento(ex.Message, "1");
                throw new FacturacionElectronicaException(ex);
            }
        }
コード例 #55
0
ファイル: B2bApi.cs プロジェクト: Fyyk-Whua/B2bApiInterface
        /// <summary>
        /// B2bApiRequestByJson
        /// </summary>
        /// <param name="moduleType">模板类型</param>
        /// <param name="requestType">请求类型</param>
        /// <param name="requestData">请求数据</param>
        /// <returns></returns>
        public string B2bApiRequestByJson(Log4netUtil.LogAppendToForms logAppendToForms,
                                          Model.JobEntity jobInfo, string requestData)
        {
            //Log4netUtil.Log4NetHelper.Info(string.Format("SendPost FyykApi RequestData{0}", requestData), @"DYZS\FyykApi");
            Newtonsoft.Json.Linq.JObject jObject;
            string logMessage = string.Empty;
            string reqUrl     = string.Format(@"{0}/{1}/{2}/{3}", _DomainName, _ServiceName, jobInfo.ApiModuleType, jobInfo.ApiRequestType);


            string stortJson = string.Empty;
            string content   = string.Empty;

            //var jArray = Newtonsoft.Json.Linq.JArray.Parse(requestData);
            //jObject = Newtonsoft.Json.Linq.JObject.Parse(requestData);
            //string jsonData = JsonConvert.SerializeObject(jObject);
            stortJson = requestData; // Util.NewtonsoftCommon.StortJson(requestData, false); //排序
            content   = requestData; // JsonConvert.SerializeObject(jObject);

            try
            {
                string sign       = SignEncrypt(stortJson, _SignKey).ToLower();
                string jsonDataEN = AesEncrypt(content, _EncryptKey);
                //string jsonDataENReplace = jsonDataEN;//  jsonDataEN.Replace("+", "%2B");//注意加号(’+‘)的替换处理,否则由于加号经过Url传递后变成空格而得不到合法的Base64字符串
                //Dictionary<string, string> param = new Dictionary<string, string>();
                //jsonDataENReplace = string.Empty;
                var requestJObject = new Newtonsoft.Json.Linq.JObject();
                requestJObject.Add("data", jsonDataEN);
                requestJObject.Add("sign", sign);

                string result = SendPost(logAppendToForms, jobInfo, reqUrl, Util.NewtonsoftCommon.SerializeObjToJson(requestJObject));
                jObject = new Newtonsoft.Json.Linq.JObject();
                jObject.Add("returl", reqUrl);
                jObject.Add("request", requestData);
                jObject.Add("result", result);// JToken.FromObject(new {result}));// Newtonsoft.Json.Linq.JObject.Parse(result));

                Newtonsoft.Json.Linq.JObject resultJObject = Newtonsoft.Json.Linq.JObject.Parse(result);
                jObject.Add("code", resultJObject.Value <int>("code"));
                if (string.Equals(resultJObject.Value <int>("code"), 200))
                {
                    jObject.Add("msg", string.Format("B2bApiRequestByJson接口调用成功!", jobInfo.JobCode, jobInfo.JobName));
                    logMessage = string.Format("【{0}_{1}】 B2bApiRequestByJson接口调用成功!\n\r {2}", jobInfo.JobCode, jobInfo.JobName, Util.NewtonsoftCommon.SerializeObjToJson(jObject));
                    Log4netUtil.Log4NetHelper.LogMessage(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
                }
                else
                {
                    jObject.Add("msg", string.Format("B2bApiRequestByJson 接口调用失败!", jobInfo.JobCode, jobInfo.JobName));
                    logMessage = string.Format("【{0}_{1}】 B2bApiRequestByJson 接口调用失败!\n\r {2}", jobInfo.JobCode, jobInfo.JobName, Util.NewtonsoftCommon.SerializeObjToJson(jObject));
                    Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
                }
                return(result);
            }catch (Exception ex)
            {
                logMessage = string.Format("【{0}_{1}】B2bApiRequestByJson接口失败 失败原因:{2}", jobInfo.JobCode, jobInfo.JobName, ex);
                Log4netUtil.Log4NetHelper.LogError(logAppendToForms, jobInfo.IsDebug, logMessage, string.Format(@"Api\{0}", jobInfo.JobCode));
                Newtonsoft.Json.Linq.JObject exJObject = new Newtonsoft.Json.Linq.JObject();
                exJObject.Add("code", 999);
                exJObject.Add("msg", ex.Message);
                exJObject.Add("data", string.Empty);
                exJObject.Add("requestUrl", reqUrl);
                exJObject.Add("request", Newtonsoft.Json.Linq.JObject.Parse(requestData));
                return(Util.NewtonsoftCommon.SerializeObjToJson(exJObject));
            }
        }
コード例 #56
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var list = context.HttpContext.Authentication.GetAuthenticationSchemes();

            foreach (var one in list)
            {
                Console.WriteLine(one.AuthenticationScheme);
            }
            Newtonsoft.Json.Linq.JObject paramjson = new Newtonsoft.Json.Linq.JObject();
            foreach (var onekey in context.RouteData.Values.Keys)
            {
                object tmp;
                context.RouteData.Values.TryGetValue(onekey, out tmp);
                if (tmp != null)
                {
                    paramjson.Add(onekey, tmp.ToString());
                }
            }
            string area, controler, action;

            if (context.RouteData.Values.Keys.Contains("area"))
            {
                area = context.RouteData.Values["area"].ToString().ToLower();
                paramjson.Remove("area");
            }
            else
            {
                area = "-1";
            }
            if (context.RouteData.Values.Keys.Contains("controller"))
            {
                controler = context.RouteData.Values["controller"].ToString().ToLower();
                paramjson.Remove("controller");
            }
            else
            {
                controler = "";
            }
            if (context.RouteData.Values.Keys.Contains("action"))
            {
                action = context.RouteData.Values["action"].ToString().ToLower();
                paramjson.Remove("action");
            }
            else
            {
                action = "";
            }
            if (area == "-1" && string.IsNullOrEmpty(controler))
            {
                context.Result = ReturnSystemError(context);
                return;
            }

            string rolestr  = "";
            string userid   = "";
            bool   isdevice = false;

            Microsoft.Extensions.Primitives.StringValues dtoken = "";
            if (context.HttpContext.Request.Headers.TryGetValue("DeviceToken", out dtoken))
            {
                if (!string.IsNullOrEmpty(dtoken))
                {
                    isdevice = true;
                }
            }
            Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
            if (context.HttpContext.User != null && context.HttpContext.User.Identity.IsAuthenticated)
            {
                ClaimsIdentity ci            = context.HttpContext.User.Identity as ClaimsIdentity;
                var            userPrincipal = new ClaimsPrincipal(ci);
                System.Threading.Thread.CurrentPrincipal = userPrincipal;
                var clm = (from x in ci.Claims where x.Type == "RoleId" select x).FirstOrDefault();
                rolestr = clm == null ? "" : clm.Value;
                clm     = (from x in ci.Claims where x.Type == "UserId" select x).FirstOrDefault();
                userid  = clm == null ? "" : clm.Value;
            }
            else
            {
                if (context.HttpContext.Request.Headers.ContainsKey("token"))
                {
                }
            }
            string paramstr = paramjson.ToString();

            if (!this._options.authorizefilter.AnonymousAllowed(controler, action,
                                                                context.HttpContext.Request.Method, paramstr, area, isdevice))
            {
                var  Caction = context.ActionDescriptor as ControllerActionDescriptor;
                bool isapi   = false;
                //控制器是继承CsApiHttpController
                if (typeof(apiController).IsAssignableFrom(Caction.ControllerTypeInfo))
                {
                    isapi = true;
                }

                bool shouldRedirct = false;
                if (string.IsNullOrEmpty(rolestr) ||
                    !this._options.authorizefilter.Isvalidtoken(userid) ||
                    !this._options.authorizefilter.IsAllowed(rolestr, controler, action,
                                                             context.HttpContext.Request.Method, paramstr, area, isdevice))
                {
                    shouldRedirct = true;
                }
                if (shouldRedirct)
                {
                    if (!isapi && _options.isWeb)
                    {
                        context.Result = ReturnRedirect(context, _options);
                    }
                    else
                    {
                        context.Result = ReturnNeedLogin(context);
                    }
                    return;
                }
            }
            //if (context.HttpContext.User.Identity.Name != "1") //只是个示范作用
            //{
            //    //未通过验证则跳转到无权限提示页
            //    RedirectToActionResult content = new RedirectToActionResult("NoAuth", "Exception", null);
            //    StatusCodeResult scr = new StatusCodeResult(400);
            //    JObject jobj = new JObject();
            //    jobj.Add("code", 100);
            //    jobj.Add("memo", "test");
            //    BadRequestObjectResult bror = new BadRequestObjectResult(jobj);
            //     context.Result = bror;
            //}
        }
    /**
     * Example of populating the Presort parameters for a mailing. Used with updateQuote<br>
     * <br>
     * @return String JSON string <br>
     */

    public string buildPresortParameters()
    {
        string json_string = "";

        /*
         * Presort parameters example
         *      {
         *          "success": "true",
         *          "presort_class": "STANDARD MAIL",
         *          "drop_zip": "93422",
         *          "mail_piece_size": "LETTER",
         *          "piece_height": "4.00",
         *          "piece_length": "5.00",
         *          "thickness_value": ".009",
         *          "thickness_based_on": "1",
         *          "tray_type": "MMM",
         *          "calculate_container_volume": "1",
         *          "min1ft": "",
         *          "max1ft": "",
         *          "min2ft": "",
         *          "max2ft": "",
         *          "print_barcode": "1",
         *          "print_imb": "1",
         *          "machinability": "NONMACHINABLE",
         *          "weight_value": ".2",
         *          "weight_unit": "OUNCES",
         *          "weight_based_on": "1",
         *          "mail_permit_type": "PROFIT",
         *          "mail_pay_method": "IMPRINT",
         *          "include_non_zip4": "1",
         *          "include_crrt": "0",
         *          "print_reverse": "0",
         *          "entry_scf": "0",
         *          "entry_ndc": "0",
         *          "agent_or_mailer_signing_statement": "STEVE BELMONTE",
         *          "agent_or_mailer_company": "ACCUZIP INC.",
         *          "agent_or_mailer_phone": "8054617300",
         *          "agent_or_mailer_email": "*****@*****.**",
         *          "mailing_agent_name_address": "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500",
         *          "mailing_agent_phone": "8054617300",
         *          "mailing_agent_mailer_id": "999999",
         *          "mailing_agent_crid": "8888888",
         *          "mailing_agent_edoc_sender_crid": "8888888",
         *          "prepared_for_name_address": "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500",
         *          "prepared_for_mailer_id": "999999",
         *          "prepared_for_crid": "8888888",
         *          "prepared_for_nonprofit_authorization_number": "",
         *          "permit_holder_name_address": "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500",
         *          "permit_holder_phone": "8054617300",
         *          "permit_holder_mailer_id": "999999",
         *          "permit_holder_crid": "8888888",
         *          "statement_number": "1",
         *          "mailing_date": "08/20/2014",
         *          "mail_permit_number": "199",
         *          "net_postage_due_permit_number": "",
         *          "postage_affixed": "",
         *          "exact_postage": "",
         *          "imb_default_mid": "999999",
         *          "imb_mid": "999999",
         *          "imb_starting_serial_number": "",
         *          "imb_service_type": "270",
         *          "json_maildat_pdr": "0",
         *          "json_maildat_mpu_name": "JOB1",
         *          "json_maildat_mpu_description": "TEST JOB",
         *          "json_accutrace_job_description": "TEST JOB",
         *          "json_accutrace_job_id": "123456",
         *          "json_accutrace_job_id2": "789",
         *          "json_accutrace_notice_email": "*****@*****.**",
         *          "json_accutrace_customer_id": "7700000101",
         *          "json_accutrace_api_key": "8B5A8632-31FC-4DA7-BDB9-D8B88897AF96",
         *          "format": "UPPER",
         *          "json_list_owner_paf_id": "E00001",
         *          "json_list_owner_information": "company|address|city|state|zip+4|telephone|naics|email|name|title|08/01/2014",
         *          "total_postage": "",
         *          "postage_saved": "",
         *          "First_Class_Card": "",
         *          "First_Class_Letter": "",
         *          "First_Class_Flat": "",
         *          "Standard_Card": "",
         *          "Standard_Letter": "",
         *          "Standard_Flat": ""
         *       }
         */

        Newtonsoft.Json.Linq.JObject jsonObj = new Newtonsoft.Json.Linq.JObject();
        jsonObj.Add("success", "true");
        jsonObj.Add("presort_class", "STANDARD MAIL");
        jsonObj.Add("drop_zip", "93422");
        jsonObj.Add("mail_piece_size", "LETTER");
        jsonObj.Add("piece_height", "4.00");
        jsonObj.Add("piece_length", "5.00");
        jsonObj.Add("thickness_value", ".009");
        jsonObj.Add("thickness_based_on", "1");
        jsonObj.Add("tray_type", "MMM");
        jsonObj.Add("calculate_container_volume", "1");
        jsonObj.Add("min1ft", "");
        jsonObj.Add("max1ft", "");
        jsonObj.Add("min2ft", "");
        jsonObj.Add("max2ft", "");
        jsonObj.Add("print_barcode", "1");
        jsonObj.Add("print_imb", "1");
        jsonObj.Add("machinability", "NONMACHINABLE");
        jsonObj.Add("weight_value", ".2");
        jsonObj.Add("weight_unit", "OUNCES");
        jsonObj.Add("weight_based_on", "1");
        jsonObj.Add("mail_permit_type", "PROFIT");
        jsonObj.Add("mail_pay_method", "IMPRINT");
        jsonObj.Add("include_non_zip4", "1");
        jsonObj.Add("include_crrt", "0");
        jsonObj.Add("print_reverse", "0");
        jsonObj.Add("entry_scf", "0");
        jsonObj.Add("entry_ndc", "0");
        jsonObj.Add("agent_or_mailer_signing_statement", "STEVE BELMONTE");
        jsonObj.Add("agent_or_mailer_company", "ACCUZIP INC.");
        jsonObj.Add("agent_or_mailer_phone", "8054617300");
        jsonObj.Add("agent_or_mailer_email", "*****@*****.**");
        jsonObj.Add("mailing_agent_name_address", "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500");
        jsonObj.Add("mailing_agent_phone", "8054617300");
        jsonObj.Add("mailing_agent_mailer_id", "999999");
        jsonObj.Add("mailing_agent_crid", "8888888");
        jsonObj.Add("mailing_agent_edoc_sender_crid", "8888888");
        jsonObj.Add("prepared_for_name_address", "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500");
        jsonObj.Add("prepared_for_mailer_id", "999999");
        jsonObj.Add("prepared_for_crid", "8888888");
        jsonObj.Add("prepared_for_nonprofit_authorization_number", "");
        jsonObj.Add("permit_holder_name_address", "Steve Belmonte|AccuZIP Inc.|3216 El Camino Real|Atascadero CA 93422-2500");
        jsonObj.Add("permit_holder_phone", "8054617300");
        jsonObj.Add("permit_holder_mailer_id", "999999");
        jsonObj.Add("permit_holder_crid", "8888888");
        jsonObj.Add("statement_number", "1");
        jsonObj.Add("mailing_date", "08/20/2014");
        jsonObj.Add("mail_permit_number", "199");
        jsonObj.Add("net_postage_due_permit_number", "");
        jsonObj.Add("postage_affixed", "");
        jsonObj.Add("exact_postage", "");
        jsonObj.Add("imb_default_mid", "999999");
        jsonObj.Add("imb_mid", "999999");
        jsonObj.Add("imb_starting_serial_number", "");
        jsonObj.Add("imb_service_type", "270");
        jsonObj.Add("json_maildat_pdr", "0");
        jsonObj.Add("json_maildat_mpu_name", "JOB1");
        jsonObj.Add("json_maildat_mpu_description", "TEST JOB");
        jsonObj.Add("json_accutrace_job_description", "TEST JOB");
        jsonObj.Add("json_accutrace_job_id", "123456");
        jsonObj.Add("json_accutrace_job_id2", "789");
        jsonObj.Add("json_accutrace_notice_email", "*****@*****.**");
        jsonObj.Add("json_accutrace_customer_id", "7700000101");
        jsonObj.Add("json_accutrace_api_key", "8B5A8632-31FC-4DA7-BDB9-D8B88897AF96");
        jsonObj.Add("format", "UPPER");
        jsonObj.Add("json_list_owner_paf_id", "E00001");
        jsonObj.Add("json_list_owner_information", "company|address|city|state|zip+4|telephone|naics|email|name|title|08/01/2014");
        jsonObj.Add("total_postage", "");
        jsonObj.Add("postage_saved", "");
        jsonObj.Add("First_Class_Card", "");
        jsonObj.Add("First_Class_Letter", "");
        jsonObj.Add("First_Class_Flat", "");
        jsonObj.Add("Standard_Card", "");
        jsonObj.Add("Standard_Letter", "");
        jsonObj.Add("Standard_Flat", "");

        json_string = jsonObj.ToString();

        return(json_string);
    }
コード例 #58
0
ファイル: TestFusions.cs プロジェクト: mmerce/bigml-csharp
        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);
        }
コード例 #59
0
        // oFn fn = new oFn();

        public async void EnvioDatos(string TK, Recepcion objRecepcion, string URL_RECEPCION)
        {
            try
            {
                //string URL_RECEPCION = "https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/";

                HttpClient http        = new HttpClient();
                string     MsgHacienda = string.Empty;

                Newtonsoft.Json.Linq.JObject JsonObject = new Newtonsoft.Json.Linq.JObject();
                JsonObject.Add(new JProperty("clave", objRecepcion.clave));
                JsonObject.Add(new JProperty("fecha", objRecepcion.fecha));
                JsonObject.Add(new JProperty("emisor",
                                             new JObject(new JProperty("tipoIdentificacion", objRecepcion.emisor.TipoIdentificacion),
                                                         new JProperty("numeroIdentificacion", objRecepcion.emisor.numeroIdentificacion))));

                if (objRecepcion.receptor.sinReceptor == false)
                {
                    JsonObject.Add(new JProperty("receptor",
                                                 new JObject(new JProperty("tipoIdentificacion", objRecepcion.receptor.TipoIdentificacion),
                                                             new JProperty("numeroIdentificacion", objRecepcion.receptor.numeroIdentificacion))));
                }

                JsonObject.Add(new JProperty("comprobanteXml", objRecepcion.comprobanteXml));
                jsonEnvio = JsonObject.ToString();

                StringContent oString = new StringContent(JsonObject.ToString());
                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));

                HttpResponseMessage response = http.PostAsync((URL_RECEPCION + "recepcion"), oString).Result;
                string res = await response.Content.ReadAsStringAsync();

                if (!response.StatusCode.ToString().Equals("Accepted"))
                {
                    iError = $"Error de Validación #: {response.StatusCode.ToString()}";
                    //mensajeRespuesta = response.Headers.GetValues["X-Error-Cause"][0].ToString();
                    statusCode = response.StatusCode.ToString();
                    return;
                }

                //object Localizacion = response.StatusCode;
                // mensajeRespuesta = Localizacion
                //IEnumerable listError = response.Headers.GetValues("X-Error-Cause").FirstOrDefault
                // string[] val = response.Headers.GetValues("").ToArray<>;

                // iError = response.Headers.GetValues("X-Error-Code").FirstOrDefault();

                //iError = (response.Headers)).headerStore["X-Error-Code"].ParsedValue();
                //string[] _err = (string[])response.Headers.GetValues("X-Error")[0];
                // Get the headers associated with the response.
                //httpWebHeaderCollection myWebHeaderCollection = response.Headers;

                //HttpResponseHeader myWebHeaderCollection = response.Headers;
                //HttpResponseMessage  myWebHeaderCollection = response.Headers;

                http = new HttpClient();
                http.DefaultRequestHeaders.Add("authorization", ("Bearer " + TK));
                response = http.GetAsync(URL_RECEPCION + "recepcion/" + objRecepcion.clave).Result;
                res      = await response.Content.ReadAsStringAsync();

                jsonRespuesta = res.ToString();

                RespuestaHacienda RH = Newtonsoft.Json.JsonConvert.DeserializeObject <RespuestaHacienda>(res);

                if (RH == null)
                {
                    estadoFactura = null;
                }
                else
                {
                    if (RH.respuesta_xml != null)
                    {
                        xmlRespuesta = Funciones.DecodeBase64ToXML(RH.respuesta_xml);
                        MsgHacienda  = xmlRespuesta.GetElementsByTagName("MensajeHacienda")[0]["DetalleMensaje"].InnerText;
                    }

                    estadoFactura = RH.ind_estado;
                }


                statusCode = response.StatusCode.ToString();

                mensajeRespuesta = ("Confirmación: " + (statusCode + Environment.NewLine));
                mensajeRespuesta = (mensajeRespuesta + ("Estado: " + estadoFactura == null ? "Sin Respuesta" : estadoFactura + Environment.NewLine));
                mensajeRespuesta = (mensajeRespuesta + ("Mensaje Hacienda: " + MsgHacienda));

                iError = "Ok";
            }
            catch (Exception ex)
            {
                iError = "Error: " + statusCode + Environment.NewLine +
                         ex.Message;

                //fn.XtraMsg("Error al Enviar XML: " + Constants.vbCrLf +
                //    ex.Message, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }