public static string Export(Replay replay)
 {
     Game game = new Game(replay);
     GameState oldState = null;
     List<GameAction> actions = new List<GameAction>();
     for (int i = 0; i < replay.Actions.Count; i++)
     {
         if (replay.Actions[i] is ReplayTimeAction)
             actions.Add(replay.Actions[i]);
         game.Seek(i);
         List<GameAction> newActions = StateDelta.Delta(oldState, game.State);
         actions.AddRange(newActions);
         if (game.State != null)
             oldState = game.State.Clone();
     }
     List<JObject> jActions = new List<JObject>();
     TimeSpan time = TimeSpan.Zero;
     foreach (var action in actions)
     {
         if (action is ReplayTimeAction)
             time = ((ReplayTimeAction)action).Time;
         else
             jActions.Add(SerializeAction(action, time));
     }
     JObject json = new JObject(new JProperty("changes", new JArray(jActions)));
     return json.ToString(Newtonsoft.Json.Formatting.None);
 }
		public static int BetRequest(JObject jsonState)
		{
			int bet = 0;
			var gameState = JsonConvert.DeserializeObject<GameState>(jsonState.ToString());
            try
			{
				string actualDecision = "none";
				Logger.LogHelper.Log("type=bet_begin action=bet_request request_id={0} game_id={1}", requestId, gameState.GameId);

				foreach (IDecisionLogic decisionLogic in Decisions.DecisionFactory.GetDecisions())
                {
                    //végigpróbáljuk a lehetőségeket
                    int? possibleBet = decisionLogic.MakeADecision(gameState);
                    if (possibleBet.HasValue)
                    {
                        bet = possibleBet.Value;
						actualDecision = decisionLogic.GetName();
                        break;
                    }
				}

				string cards = String.Join(",", gameState.OwnCards);
				Logger.LogHelper.Log("type=bet action=bet_request request_id={0} game_id={1} bet={2} cards={3} decision={4}",
					requestId, gameState.GameId, bet, cards, actualDecision);
            }
            catch (Exception ex)
            {
				Logger.LogHelper.Error("type=error action=bet_request request_id={0} game_id={1} error_message={2}",requestId, gameState.GameId, ex);
            }

			return bet;
		}
 public ItemListStatic(JObject basicO,
     JObject dataO,
     JArray groupsA,
     JArray treeA,
     string type,
     string version,
     JObject originalObject)
 {
     data = new Dictionary<string, ItemStatic>();
     groups = new List<GroupStatic>();
     tree = new List<ItemTreeStatic>();
     if (basicO != null)
     {
         basic = HelperMethods.LoadBasicDataStatic(basicO);
     }
     if (dataO != null)
     {
         LoadData(dataO.ToString());
     }
     if (groupsA != null)
     {
         LoadGroups(groupsA);
     }
     if (treeA != null)
     {
         LoadTree(treeA);
     }
     this.type = type;
     this.version = version;
     this.originalObject = originalObject;
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     Response.Clear();
     var obj = new JObject(new JProperty("machineName", ServerManager.MachineName), new JProperty("servers", JArray.FromObject(ServerManager.GetActiveServerList())));
     Response.BinaryWrite(Encoding.UTF8.GetBytes(obj.ToString()));
     Response.End();
 }
Exemple #5
0
        public async void _GetMesagges()
        {
            Utils  utils         = new Utils();
            string URL_RECEPCION = utils.GetConfigFromXML("URL_RECEPCION");

            HttpClient http = new HttpClient();

            Newtonsoft.Json.Linq.JObject JsonObject = new Newtonsoft.Json.Linq.JObject();
            jsonEnvio = JsonObject.ToString();
            StringContent oString = new StringContent(JsonObject.ToString());

            try
            {
                HttpResponseMessage response = http.GetAsync((URL_RECEPCION)).Result;
                string res = await response.Content.ReadAsStringAsync();

                if (response.StatusCode.ToString() == "OK")
                {
                    jsonRespuesta = res.ToString();
                    ResponseList  = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Message> >(res);
                }
                else
                {
                    ResponseList = null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 //post方式调用服务器接口
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     //填写查寻密钥
     string queryKey = "abc";
     //定义要访问的云平台接口--接口详见服务器开发文档
     string uri="/api/20140928/management";
     DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
     long Sticks = (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
     string timeStamp = Sticks.ToString();
     //填写服务器提供的服务码
     string queryString = "service_code=TESTING";
     WoanSignature.Signature Signature = new WoanSignature.Signature();
     //定义请求数据,以下json是一个删除文件的json请求
     JObject json = new JObject(
         new JProperty("function", "delete_video"),
         new JProperty("params",
             new JObject(
             new JProperty("service_code", "TESTING"),
             new JProperty("file_name", "1.m3u8")
             )
          )
     );
     string signature = Signature.SignatureForPost(uri, queryKey, queryString, json.ToString(), timeStamp);
      WoanSignature.HttpTool HttpTool = new WoanSignature.HttpTool();
      string response = HttpTool.post("http://c.zhiboyun.com/api/20140928/management?" + queryString, signature, timeStamp, json.ToString());
     MessageBox.Show(response);
 }
		public void ProcessRequestAsyncSuccessfully()
		{
			JObject returnValue = new JObject { { "Name", "TestName" } };

			Uri requestUri =
				new Uri(
					string.Format(
						"http://bla.com/api/{0}/{1}?{2}=TestValue1",
						WebApiConfiguration.Instance.Apis[0].Name,
						WebApiConfiguration.Instance.Apis[0].WebMethods[0].Name,
						WebApiConfiguration.Instance.Apis[0].WebMethods[0].Parameters[0].Name));

			Mock<IRunner> runnerMock = new Mock<IRunner>(MockBehavior.Strict);
			runnerMock.Setup(
				m => m.ExecuteAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>(), It.IsAny<bool>()))
				.ReturnsAsync(new PowershellReturn
				{
					PowerShellReturnedValidData = true,
					ActualPowerShellData = returnValue.ToString()
				});

			var ioc = createContainer(cb => cb.RegisterInstance(runnerMock.Object));

			var genericController = ioc.Resolve<GenericController>();
			genericController.Request = new HttpRequestMessage(HttpMethod.Get, requestUri);
			var res = genericController.ProcessRequestAsync().Result;

			Assert.AreEqual(
				returnValue.ToString(),
				res.Content.ReadAsStringAsync().Result,
				"Return value from process request is incorrect");
		}
Exemple #8
0
        public System.Data.DataSet GetDataSet(Newtonsoft.Json.Linq.JObject obj, string ActionType = "Select")
        {
            var data = post(obj.ToString());

            bool LoginOl = ((data == "401") || (data.Contains("not found") || data.Contains("LoginToken")) || data.Contains("LoginToken is invalid"));

            if (LoginOl == true)
            {
                Login();
                obj["LoginToken"] = this.LoginToken;
                data = post(obj.ToString());
            }

            var datasource = new JObject();

            if (ActionType == "Select")
            {
                if (!data.Contains("{") || !data.Contains("}"))
                {
                    System.Windows.Forms.MessageBox.Show(data.ToString(), "ElektraWeb", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    throw null;
                }
                JArray dataSets = new JArray();

                dataSets = (JArray)JObject.Parse(data)["ResultSets"];

                try
                {
                    dataSets = (JArray)JObject.Parse(data)["ResultSets"];
                }
                catch (Exception)
                {
                    MessageBox.Show("Error Occurred :" + data);
                    throw;
                }
                datasource["datatable1"] = JObject.Parse(data)["ResultSets"][0];
            }
            else if (ActionType == "Execute")
            {
                if (!data.Contains("]") || !data.Contains("["))
                {
                    System.Windows.Forms.MessageBox.Show(data.ToString(), "ElektraWeb", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    throw null;
                }
                JArray dataSets = new JArray();
                dataSets = JArray.Parse(data);
                var _obj = JArray.Parse(data);
                datasource["datatable1"] = _obj[0]; //JObject.Parse(data)[0];
            }


            var datasourceStr = Newtonsoft.Json.JsonConvert.SerializeObject(datasource, new Newtonsoft.Json.JsonSerializerSettings {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
            });

            System.Data.DataSet dataset = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Data.DataSet>(datasourceStr);
            return(dataset);

            //System.Data.DataTable datatable = dataset.Tables["datatable1"];
        }
        public void VerifyFlagsEnum()
        {
            Type typeToTest = typeof(PaletteFlags);
            var typeExpected = new JObject(
                new JProperty("type", "#/PaletteFlags")
                ).ToString();

            var schemaExpected = new JObject(
                new JProperty("PaletteFlags",
                    new JObject(new JProperty("id", "#/PaletteFlags"),
                        new JProperty("type", "number"),
                        new JProperty("format", "bitmask"),
                        new JProperty("enum", new JArray(1, 2, 4)),
                        new JProperty("options", new JArray(
                            new JObject(new JProperty("value", 1), new JProperty("label", "HasAlpha")),
                            new JObject(new JProperty("value", 2), new JProperty("label", "GrayScale")),
                            new JObject(new JProperty("value", 4), new JProperty("label", "Halftone"))
                    ))))
                ).ToString();

            const bool flatten = false;
            var schema = new JObject();
            string actual = GetActual(typeToTest, typeExpected, flatten, schema);

            Assert.AreEqual(typeExpected, actual);

            Console.WriteLine("SCHEMA\n" + schema.ToString(Formatting.Indented));
            Assert.AreEqual(schemaExpected, schema.ToString(Formatting.Indented));
        }
Exemple #10
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string[] props = new string[] { "EntryId", "DateCreated", "CreatedBy", "DateUpdated", "UpdatedBy" };

            JObject orig = JObject.Load(reader);
            JObject result = new JObject();
            JObject responses = new JObject();

            foreach (string p in props)
            {
                result[p] = orig[p];
                orig.Remove(p);
            }

            foreach (var prop in orig.Properties())
            {
                responses[prop.Name] = prop.Value;
            }
            result.Add("Fields", responses);

            var outString = result.ToString();
            Entry e = new Entry();
            JsonConvert.PopulateObject(result.ToString(), e);

            return e;
        }
        public void VerifyEnum()
        {
            Type typeToTest = typeof(Duplex);
            var typeExpected = new JObject(new JProperty("type", "#/Duplex")).ToString();
            var schemaExpected = new JObject(
                    new JProperty("Duplex", 
                        new JObject(
                            new JProperty("id", "#/Duplex"),
                            new JProperty("type", "number"),
                            new JProperty("enum", new JArray(1, 2, 3, -1)),
                            new JProperty("options", new JArray(
                                new JObject(new JProperty("value", 1), new JProperty("label", "Simplex")),
                                new JObject(new JProperty("value", 2), new JProperty("label", "Vertical")),
                                new JObject(new JProperty("value", 3), new JProperty("label", "Horizontal")),
                                new JObject(new JProperty("value", -1), new JProperty("label", "Default"))
                        ))))

                    ).ToString();

            const bool flatten = false;
            var schema = new JObject();
            string actual = GetActual(typeToTest, typeExpected, flatten, schema);

            Assert.AreEqual(typeExpected, actual);

            Console.WriteLine("SCHEMA\n" + schema.ToString(Formatting.Indented));
            Assert.AreEqual(schemaExpected, schema.ToString(Formatting.Indented));
        }
        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;
            }
        }
Exemple #13
0
        internal static NIMIMMessage CreateMessage(Newtonsoft.Json.Linq.JObject token)
        {
            if (!token.HasValues || token.Type != Newtonsoft.Json.Linq.JTokenType.Object)
            {
                return(null);
            }
            var msgTypeToken = token.SelectToken(NIMIMMessage.MessageTypePath);

            if (msgTypeToken == null)
            {
                throw new ArgumentException("message type must be seted:" + token.ToString(Formatting.None));
            }
            var          msgType = msgTypeToken.ToObject <NIMMessageType>();
            NIMIMMessage message = null;

            ConvertAttachStringToObject(token);
            switch (msgType)
            {
            case NIMMessageType.kNIMMessageTypeAudio:
                message = token.ToObject <NIMAudioMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeFile:
                message = token.ToObject <NIMFileMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeImage:
                message = token.ToObject <NIMImageMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeLocation:
                message = token.ToObject <NIMLocationMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeText:
                message = token.ToObject <NIMTextMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeVideo:
                message = token.ToObject <NIMVedioMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeNotification:
                message = token.ToObject <NIMTeamNotificationMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeCustom:
                message = token.ToObject <NIMCustomMessage <object> >();
                break;

            default:
                message = new NIMUnknownMessage();
                ((NIMUnknownMessage)message).RawMessage = token.ToString(Formatting.None);
                break;
            }
            return(message);
        }
 public void SendMessage(string targetId, string senderId, JObject jobj, ConversationType type)
 {
     if (type == ConversationType.PRIVATE)
     {
         int messageId = Rcsdk.SaveMessage(targetId, 1, "RC:TxtMsg", senderId, jobj.ToString(), "", "", false, 0);
         Rcsdk.sendMessage(targetId, 1, 2, "RC:TxtMsg", jobj.ToString(), "", "", messageId, _sendCallBack);
     }
     else if (type == ConversationType.DISCUSSION)
     {
         int messageId1 = Rcsdk.SaveMessage(targetId, 2, "RC:TxtMsg", senderId, jobj.ToString(), "", "", false, 0);
         Rcsdk.sendMessage(targetId, 2, 3, "RC:TxtMsg", jobj.ToString(), "", "", messageId1, _sendCallBack);
     }
 }
	    public void invalidParams_platform() {
            JObject payload = new JObject();
	        payload.Add("platform", JToken.FromObject("all_platform"));
            payload.Add("audience", JToken.FromObject(JsonConvert.SerializeObject(Audience.all(), new AudienceConverter())));
            payload.Add("notification", JToken.FromObject(new  Notification().setAlert(ALERT)));

            Console.WriteLine("json string: " + payload.ToString());
	        
	        try {
                var result = _client.SendPush(payload.ToString());
	        } catch (APIRequestException e) {
                 Assert.AreEqual(INVALID_PARAMS, e.ErrorCode);
	        }
	    }
        async static Task SetHostname(string NewHostname)
        {
            //create the URI for Netscaler login
            string nsURI = string.Format(@"http://{0}:{1}/nitro/v1/config/nshostname", NSAddress, NSPort);

            Console.WriteLine("Connecting to " + nsURI);

            //Create new http client for requests
            HttpClient _client = new HttpClient();

            _client.DefaultRequestHeaders.Add("X-NITRO-USER", NSUsername);
            _client.DefaultRequestHeaders.Add("X-NITRO-PASS", NSPassword);

            Newtonsoft.Json.Linq.JObject _hostname = Newtonsoft.Json.Linq.JObject.FromObject(new
            {
                nshostname = new { hostname = NewHostname }
            });

            //creating the body content that needs to be sent with the HTTP POST.
            HttpContent _hostnameBody = new StringContent(_hostname.ToString(), Encoding.ASCII, @"application/json");

            //setting the content type to application/json for the request. Important!
            _hostnameBody.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            //Posting the credentials to the endpoint
            System.Net.Http.HttpResponseMessage _msg = await _client.PutAsync(nsURI, _hostnameBody);

            //Reading the content back from the response. This could contain an error message but for
            //simplicity, this example does trap for that.
            string _responseJson = await _msg.Content.ReadAsStringAsync();

            Console.WriteLine("Return value from Netscaler CPX Set Hostname API");
            Console.WriteLine(_responseJson);
        }
        public RequestForm makeRequestForm(JObject json)
        {
            string currManagerName = (string)json["current"]["bazookaInfo"]["managerId"];
            string futureManagerName = (string)json["future"]["bazookaInfo"]["managerId"];
            int managerID = GetIDFromName(currManagerName);
            int f_managerID = GetIDFromName(futureManagerName);
            json["current"]["bazookaInfo"]["managerId"] = managerID;
            json["current"]["ultiproInfo"]["supervisor"] = managerID;
            json["future"]["bazookaInfo"]["managerId"] = f_managerID;
            json["future"]["ultiproInfo"]["supervisor"] = f_managerID;

            UserController uc = new UserController();
            string[] name = uc.GetUserName().Split('.');
            string creatorName = name[0] + " " + name[1];
            int creatorID = GetIDFromName(creatorName);

            RequestForm obj = null;
            using (var sr = new StringReader(json.ToString()))
            using (var jr = new JsonTextReader(sr))
            {
                var js = new JsonSerializer();
                obj = (RequestForm)js.Deserialize<RequestForm>(jr);
            }
            obj.EmployeeId = GetIDFromName((string)json["name"]);
            obj.CreatedByID = creatorID;
            obj.Current.BazookaInfo.SecurityItemRights = "";
            obj.ReviewInfo.FilesToBeRemovedFrom = "(" + obj.Current.BazookaInfo.Group + ")" + currManagerName.Replace(" ", ".")+" "+obj.ReviewInfo.FilesToBeRemovedFrom;
            obj.ReviewInfo.FilesToBeAddedTo = "(" + obj.Future.BazookaInfo.Group + ")" + futureManagerName.Replace(" ", ".")+" "+obj.ReviewInfo.FilesToBeAddedTo;

            return obj;
        }
        public void DataReceived(JObject data)
        {
            if (data["msg"] != null)
            {

                switch (data["msg"].ToString())
                {
                    case "connected":
                        // stuff that occurs on connection such as subscription if desired
                        //this.Subscribe("requests");
                        break;

                    case "added":
                        Console.WriteLine("Document Added: " + data["id"]);

                        break;
                    case "ready":
                        Console.WriteLine("Subscription Ready: " + data["subs"].ToString());
                        break;
                    case "removed":
                        Console.WriteLine("Document Removed: " + data["id"]);
                        break;

                    default:
                        Console.WriteLine(data.ToString());
                        break;
                }
            }
        }
        public List<ItemRecommendation> GetItemRankings(string userId, string[] itemIds)
        {
            if (!itemIds.Any())
            {
                throw new InvalidOperationException("Must have at least one itemId");
            }
            var request = new JObject();
            request[Constants.UserId] = userId;
            var jItems = new JArray();
            foreach (var itemId in itemIds)
            {
                jItems.Add(itemId);
            }
            request[Constants.ItemIds] = jItems;
            var body = request.ToString(Formatting.None);
            var response = (JObject)Execute(Constants.EngineResource, Method.POST, body);
            if (response[Constants.IsOriginal].Value<bool>())
            {
                return new List<ItemRecommendation>();
            }
            var recommendations = new List<ItemRecommendation>();
            foreach (var item in response[Constants.Items])
            {
                var property = item.First.Value<JProperty>();
                var recommendation = new ItemRecommendation
                {
                    ItemId = property.Name,
                    Score = item.First.First.Value<float>()
                };
                recommendations.Add(recommendation);
            }
            return recommendations;

        }   
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["Authentication"] == null)
                throw new Exception("Ошибка обновления");

            int ShopId = Convert.ToInt32(context.Session["ShopId"]);
            int ArticleId = Convert.ToInt32(context.Request["ArticleId"]);

            var dsStatistic = new dsStatistic();
            (new DataSets.dsStatisticTableAdapters.taSalesHistory()).Fill
                (dsStatistic.tbSalesHistory, ShopId, ArticleId);

            var JHistory = new JArray();
            foreach (dsStatistic.tbSalesHistoryRow rw in dsStatistic.tbSalesHistory)
                JHistory.Add(new JObject(
                    new JProperty("Дата_продажи",rw.Дата_продажи),
                    new JProperty("Номер_чека", rw.Номер_чека),
                    new JProperty("Количество", rw.Количество),
                    new JProperty("ПрИнфо", rw.ПрИнфо),
                    new JProperty("Инфо", rw.Инфо)
                    ));

            var JObject = new JObject(
                new JProperty("Код_артикула", ArticleId),
                new JProperty("История", JHistory));

            context.Response.ContentType = "application/json";
            context.Response.Write(JObject.ToString());
        }
        public void Handle_WhenAuthenticityIsTrue_ShouldReturnTrue()
        {
            // Arrange
            var verifiedResponse = new JObject(
                new JProperty("jsonrpc", "2.0"),
                new JProperty("result",
                    new JObject(
                        new JProperty("authenticity", true))
                    ),
                new JProperty("id", 1234)
                );

            Mock<IRandomService> serviceMock = new Mock<IRandomService>();
            serviceMock.Setup(m => m.SendRequest(It.IsAny<string>())).Returns(verifiedResponse.ToString);

            var input = new JObject(
                new JProperty("jsonrpc", "2.0"),
                new JProperty("result",
                    new JObject(
                        new JProperty("random", new JObject()))
                    )
                );

            // Act
            VerifySignatureHandler target = new VerifySignatureHandler(serviceMock.Object);
            var actual = target.Handle(null, input.ToString());

            // Assert
            actual.Should().Be.True();
        }
 public static async Task<bool> TryHitMetricsEndPoint(JObject jObject)
 {
     try
     {
         using (var httpClient = new System.Net.Http.HttpClient())
         {
             var response = await httpClient.PostAsync(new Uri(MetricsServiceUri + MetricsDownloadEventMethod), new StringContent(jObject.ToString(), Encoding.UTF8, ContentTypeJson));
             //print the header 
             Console.WriteLine("HTTP status code : {0}", response.StatusCode);
             if (response.StatusCode == HttpStatusCode.Accepted)
             {
                 return true;
             }
             else
             {
                 return false;
             }
         }
     }
     catch (HttpRequestException hre)
     {
         Console.WriteLine("Exception : {0}", hre.Message);
         return false;
     }
 }
Exemple #23
0
        public async static Task<bool> Ping(ConnectionItem connectionItem)
        {
            JObject requestObject = new JObject(
                new JProperty("jsonrpc", "2.0"),
                new JProperty("id", 234),
                new JProperty("method", "JSONRPC.ping"));
                
            string requestData = requestObject.ToString();

            HttpClientHandler handler = new HttpClientHandler();
            HttpClient httpClient = new HttpClient(handler);
            string uriString = "http://" + connectionItem.IpAddress + ":" + connectionItem.Port.ToString() + "/jsonrpc?request=";
            httpClient.BaseAddress = new Uri(uriString);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");

            request.Content = new StringContent(requestData);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //Required to be recognized as valid JSON request.

            HttpResponseMessage response = await httpClient.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
            if (responseString.Length == 0)
                return false;
            dynamic responseObject = JObject.Parse(responseString);
            bool isSuccessful = responseObject.result == "pong";
            return isSuccessful;
        }
        public virtual DismissMovieResult DismissShow(string apiKey, string username, string passwordHash, string imdbId = null, int? tvdbId = null, string title = null, int? year = null)
        {
            var url = String.Format("{0}{1}", Url.RecommendationsShowsDismiss, apiKey);

            var postJson = new JObject();
            postJson.Add(new JProperty("username", username));
            postJson.Add(new JProperty("password", passwordHash));

            if (imdbId != null)
                postJson.Add(new JProperty("imdb_id", imdbId));

            if (tvdbId != null)
                postJson.Add(new JProperty("tvdb_id", tvdbId));

            if (title != null)
                postJson.Add(new JProperty("title", title));

            if (year != null)
                postJson.Add(new JProperty("year", year));

            var responseJson = _httpProvider.DownloadString(url, postJson.ToString());

            if (String.IsNullOrWhiteSpace(responseJson))
                return null;

            return JsonConvert.DeserializeObject<DismissMovieResult>(responseJson);
        }
Exemple #25
0
        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>();
        }
Exemple #26
0
        public object ToEditorModel(Element element, DescribeElementsContext describeContext) {
            var map = GetMapFor(element);
            var node = new JObject();
            var container = element as Container;

            // We want to convert any null value being added to this node to an empty string,
            // so that we can perform a JSON string comparison on the client side editor to detect if the user changed anything.
            // If the initial state would contain null values, these would become empty strings after the user made a change
            // (e.g. setting some HtmlID property from empty to "my-id" and then clearing out that field).
            node.PropertyChanged += (sender, args) => {
                var value = node[args.PropertyName] as JValue;

                if (value != null && value.Value == null)
                    node[args.PropertyName] = "";
            };

            map.FromElement(element, describeContext, node);
            node["type"] = map.LayoutElementType;

            if (container != null)
                node["children"] = new JArray(container.Elements.Select(x => ToEditorModel(x, describeContext)).ToList());

            // Would be nicer if we could turn JObject into an anonymous object directly, but this seems to be the only way.
            return JsonConvert.DeserializeObject(node.ToString());
        }
        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);
            }
        }
		public override void Serialize(string path, TiledNavMesh mesh)
		{
			JObject root = new JObject();

			root.Add("meta", JToken.FromObject(new
			{
				version = new
				{
					
					snj = FormatVersion,
					sharpnav = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion
				}
			}));

			root.Add("origin", JToken.FromObject(mesh.Origin, serializer));
			root.Add("tileWidth", JToken.FromObject(mesh.TileWidth, serializer));
			root.Add("tileHeight", JToken.FromObject(mesh.TileHeight, serializer));
			root.Add("maxTiles", JToken.FromObject(mesh.MaxTiles, serializer));
			root.Add("maxPolys", JToken.FromObject(mesh.MaxPolys, serializer));

			var tilesArray = new JArray();

			var tiles = (List<MeshTile>) GetPrivateField(mesh, typeof(TiledNavMesh), "tileList");
			var tileRefs = (Dictionary<MeshTile, int>)GetPrivateField(mesh, typeof(TiledNavMesh), "tileRefs");
			foreach (MeshTile tile in tiles)
			{
				tilesArray.Add(SerializeMeshTile(tile));
			}

			root.Add("tiles", tilesArray);
			
			File.WriteAllText(path, root.ToString());
		}
 public void testQuickAlert()
 {
     WinphoneNotification winphone = new WinphoneNotification().setAlert("aaa");
     JObject json = new JObject();
     json.Add("alert", JToken.FromObject("aaa"));
     Assert.AreEqual(json.ToString(Formatting.None), JsonConvert.SerializeObject(winphone, jSetting));
 }
Exemple #30
0
        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;
        }
        //TODO: (ErikPo) Make this async
        public HttpResponseMessage Post(JObject facebookObject)
        {
#if Debug
            Utilities.Log(facebookObject.ToString());
#endif
            //TODO: (ErikPo) Find out for sure if we need to validate the request here during the security review

            //TODO: (ErikPo) This code needs to move into some sort of user change handler
            if (facebookObject["object"].Value<string>() == "user")
            {
                foreach (var entry in facebookObject["entry"])
                {
                    var facebookId = entry["id"].Value<string>();
                    var fields = new List<string>();
                    foreach (var changedField in entry["changed_fields"])
                    {
                        fields.Add(changedField.Value<string>());
                    }
                    if (fields.Count > 0)
                    {
                        var user = facebookUserStorageService.GetUser(facebookId);
                        if (user != null)
                        {
                            facebookService.RefreshUserFields(user, fields.ToArray());
                            FacebookUserEvents.FireUserChangedEvent(user);
                        }
                    }
                }
            }

            //TODO: (ErikPo) Parse other stuff like friend changes

            return Request.CreateResponse(HttpStatusCode.OK);
        }
 public void MostSimple() {
     //Note:  This is a slightly unusual situation, in that the act of putting a new
     //value into the Id property of the view model effectively creates a different view model instance!
     //so the 'self' link url has changed!
     var body = new JObject(new JProperty("Id", new JObject(new JProperty("value", 123))));
     Object(Urls.VMMostSimple + key1, "MostSimpleViewModel", body.ToString(), Methods.Put);
 }
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["Authentication"] == null)
                throw new Exception("Ошибка обновления");

            int ArticleId = Convert.ToInt32(context.Request["articleId"]);
            int ShopId = Convert.ToInt32(context.Session["ShopId"]);

            var dsReceipt = new dsReceipt();
            (new DataSets.dsReceiptTableAdapters.taSelect()).Fill
                (dsReceipt.tbSelect, ShopId, ArticleId);

            var JContent = new JArray();
            foreach (dsReceipt.tbSelectRow rw in dsReceipt.tbSelect)
                JContent.Add(new JObject(
                    new JProperty("Код_размещения", rw.Код_размещения),
                    new JProperty("ПрИнфо", rw.ПрИнфо),
                    new JProperty("Инфо", rw.Инфо),
                    new JProperty("Аббревиатура", rw.Аббревиатура),
                    new JProperty("Количество", rw.Количество)));

            var JObject = new JObject(
                new JProperty("Код_артикула", ArticleId),
                new JProperty("Позиции", JContent));

            context.Response.ContentType = "application/json";
            context.Response.Write(JObject.ToString());
        }
        public void invalidParams_audience() 
        {
            JObject payload = new JObject();
            payload.Add("platform", JToken.FromObject(JsonConvert.SerializeObject(Platform.all(), new PlatformConverter())));
            payload.Add("audience", JToken.FromObject("all_audience"));
            JsonSerializer jsonSerializer = new JsonSerializer();
            jsonSerializer.DefaultValueHandling = DefaultValueHandling.Ignore;
            payload.Add("notification", JToken.FromObject(new Notification().setAlert(ALERT), jsonSerializer));

            Console.WriteLine("json string: " + payload.ToString());
            try {
                 var result = _client.SendPush(payload.ToString());
            }catch (APIRequestException e) {
                 Assert.AreEqual(INVALID_PARAMS, e.ErrorCode);
	        }
         }
        public void TryConvertJson_JsonObjectString()
        {
            JObject child = new JObject
            {
                { "Name", "Mary" },
                { "Location", "Seattle" },
                { "Age", 5 }
            };

            JObject parent = new JObject
            {
                { "Name", "Bob" },
                { "Location", "Seattle" },
                { "Age", 40 },
                { "Children", new JArray(child) }
            };

            object result;
            string input = parent.ToString();
            bool didConvert = NodeFunctionInvoker.TryConvertJson(input, out result);
            Assert.True(didConvert);

            var resultDictionary = (IDictionary<string, object>)result;
            var resultChildren = (IEnumerable<object>)resultDictionary["Children"];
            var resultChild = (IDictionary<string, object>)resultChildren.ElementAt(0);
            Assert.Equal(5, (long)resultChild["Age"]);
        }
Exemple #36
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;
            }
        }
        public JsonResult DesignSurvey(string content)
        {
            Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
            long   id     = jobject.GetStringValue("survey_id").ToInt();
            Survey survey = _dbContext.Get <Survey>(id);

            survey.SurName     = jobject.GetStringValue("survey_name");
            survey.SurContent  = jobject.GetStringValue("test_content");
            survey.JSONContent = jobject.ToString();
            //同时生成预览视图
            _surveyService.PreviewSurvey(survey);
            _dbContext.Update(survey);
            return(Json(ResponseViewModelUtils.Sueecss()));
        }
Exemple #38
0
        protected override void MessageReceivedHandler(Newtonsoft.Json.Linq.JObject jsonMessage)
        {
            if (_manager.Config.Filters != null)
            {
                ApplyFilters(jsonMessage);
            }

            var message = jsonMessage.ToString();

            LogManager.GetCurrentClassLogger().Debug(message);

            lock (_locker)
            {
                _jsonQueue.Add(jsonMessage);
            }
        }
Exemple #39
0
        protected override void MessageReceivedHandler(Newtonsoft.Json.Linq.JObject jsonMessage)
        {
            if (_manager.Config.Filters != null)
            {
                if (ApplyFilters(jsonMessage))
                {
                    return;
                }
            }

            var message = jsonMessage.ToString();

            lock (_locker)
            {
                _jsonQueue.Add(jsonMessage);
            }
        }
Exemple #40
0
 public Boolean AddEmp([FromBody] Newtonsoft.Json.Linq.JObject value)
 {
     try
     {
         var      mystr = JObject.Parse(value.ToString());
         Employee emp   = new Employee();
         emp.Name  = mystr["Name"].ToString();
         emp.Title = mystr["Title"].ToString();
         emp.Email = mystr["Email"].ToString();
         testEntities db = new testEntities();
         db.Employees.Add(emp);
         db.SaveChanges();
         return(true);
     }
     catch (Exception e) {
         return(false);
     }
 }
Exemple #41
0
        /// <summary>
        /// Code snippet to send notifications from webjob.
        /// </summary>
        public static void SendNotification(string PushToken)
        {
            Console.WriteLine("Sending Notification to {0}", PushToken);

            var url         = string.Format("https://api.push.apple.com/3/device/{0}", PushToken);//[deviceToken]//"fddf54151c3f1a03872f66d61db12779c010f9d19bc01963a3c152033abc35d3"
            var certData    = System.IO.File.ReadAllBytes("Certificates.p12");
            var certificate = new X509Certificate2(certData, "Clearz14/11", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var topic       = "pass.app.brainchanger.io"; // App bundle Id

            using var httpHandler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 };
            httpHandler.ClientCertificates.Add(certificate);

            using var httpClient = new HttpClient(httpHandler, true);
            using var request    = new HttpRequestMessage(HttpMethod.Post, url);
            request.Headers.Add("apns-id", Guid.NewGuid().ToString("D"));
            request.Headers.Add("apns-push-type", "alert");
            //request.Headers.Add("apns-priority", "10");
            request.Headers.Add("apns-topic", topic);

            var payload = new Newtonsoft.Json.Linq.JObject {
                {
                    "aps", new Newtonsoft.Json.Linq.JObject
                    {
                    }
                }
            };

            request.Content = new StringContent(payload.ToString());
            request.Version = new Version(2, 0);
            try
            {
                using var httpResponseMessage = httpClient.SendAsync(request).GetAwaiter().GetResult();
                var responseContent = httpResponseMessage.Content.ReadAsStringAsync();
                //return $"status: {(int)httpResponseMessage.StatusCode} content: {responseContent}";
                Console.WriteLine((int)httpResponseMessage.StatusCode);
                Console.WriteLine(responseContent);
            }
            catch (Exception e)
            {
                //this._logger.LogError("send push notification error", e);
                Console.WriteLine("send push notification error::: " + e.Message);
                throw;
            }
        }
Exemple #42
0
        public Boolean EditEmp([FromBody] Newtonsoft.Json.Linq.JObject value)
        {
            var mystr = JObject.Parse(value.ToString());
            int id    = int.Parse(mystr["ID"].ToString());

            if (id != null)
            {
                testEntities db    = new testEntities();
                var          Query = from Employee in db.Employees
                                     where Employee.ID == id
                                     select Employee;
                Employee emp = Query.Single();
                emp.Name  = mystr["Name"].ToString();
                emp.Title = mystr["Title"].ToString();
                emp.Email = mystr["Email"].ToString();
                db.SaveChanges();
                return(true);
            }
            return(false);
        }
Exemple #43
0
        static int _getCount()
        {
            if (wc == null)
            {
                wc = new System.Net.WebClient();
            }
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            //var getcounturl = url + "?jsonrpc=2.0&id=1&method=getblockcount&params=[]";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "getblockcount";
            upparam["params"]  = new Newtonsoft.Json.Linq.JArray();

            var info  = wc.UploadString(url, upparam.ToString());
            var json  = Newtonsoft.Json.Linq.JObject.Parse(info);
            var count = (int)json["result"];

            return(count);
        }
Exemple #44
0
 /// <summary>
 /// 初始化主账号
 /// </summary>
 /// <param name="account">账户名</param>
 /// <param name="password">密码明文</param>
 public void InitAccount(string account, string password, string passWordHelp, string remark, bool isComputer)
 {
     //1、创建目录
     System.IO.Directory.CreateDirectory(BasePath + "data\\" + account);
     //2、创建主账号配置文件
     Newtonsoft.Json.Linq.JToken jtoken = new Newtonsoft.Json.Linq.JObject();
     jtoken["Account"]             = account;
     jtoken["Remark"]              = remark;
     jtoken["PassWordHelp"]        = passWordHelp;
     jtoken["PassWordCertificate"] = GetPassWordCertificate(account, password, isComputer);
     jtoken["Phone"]         = "";
     jtoken["Email"]         = "";
     jtoken["CreateDate"]    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
     jtoken["IsComputer"]    = isComputer;
     jtoken["PassWordBooks"] = new Newtonsoft.Json.Linq.JArray();
     IFileServer.SavePropertyFile(jtoken.ToString(), string.Format("{0}data\\{1}\\{1}.json", BasePath, account));
     //3、设置配置文件。设置默认账号
     //4、加载默认账号
     RefreshAccount();
 }
Exemple #45
0
 public Boolean DelteEmp([FromBody] Newtonsoft.Json.Linq.JObject value)
 {
     try
     {
         var          mystr  = JObject.Parse(value.ToString());
         int          id     = int.Parse(mystr["ID"].ToString());
         testEntities db     = new testEntities();
         Employee     objEmp = new Employee()
         {
             ID = id
         };
         db.Employees.Attach(objEmp);
         db.Employees.Remove(objEmp);
         db.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Exemple #46
0
        static JArray CallScript(byte[] script)
        {
            if (wc == null)
            {
                wc = new System.Net.WebClient();
            }
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "invokescript";
            var _params = new Newtonsoft.Json.Linq.JArray();

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

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

            return(result);
            //Console.WriteLine(info);
        }
Exemple #47
0
        public void SendMessage(Message message, MessageReplyCallback replyCallback)
        {
            log.DebugFormat("Sending message \"{0}\"", message["message"]);

            if (replyCallback != null)
            {
                outstandingCallbacks.Add(new MessageCallbackInfo()
                {
                    MessageName = message["message"].ToString(),
                    Callback    = replyCallback,
                    ExpireTick  = Environment.TickCount + 1000 * 10,
                    Tag         = message["tag"].ToString(),
                });
            }

            var rawData = Encoding.UTF8.GetBytes(message.ToString(Formatting.None, null) + "\r\n");

            // TODO: Handle the stream ending
            source.Write(rawData, 0, rawData.Length);

            log.Debug("...Done");
        }
        async static Task Authenticate()
        {
            //create the URI for Netscaler login
            string nsURI = string.Format(@"http://{0}:{1}/nitro/v1/config/login", NSAddress, NSPort);

            Console.WriteLine("Connecting to " + nsURI);

            //Create new http client for requests
            HttpClient _client = new HttpClient();

            //creating the JSON login object.
            //format should be {"login": {"username":"******","password":"******"}}
            Newtonsoft.Json.Linq.JObject _login = Newtonsoft.Json.Linq.JObject.FromObject(new
            {
                login = new { username = NSUsername, password = NSPassword }
            });

            //creating the body content that needs to be sent with the HTTP POST.
            HttpContent _loginBody = new StringContent(_login.ToString(), Encoding.ASCII, @"application/json");

            //setting the content type to application/json for the request. Important!
            _loginBody.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            //Posting the credentials to the endpoint
            System.Net.Http.HttpResponseMessage _msg = await _client.PostAsync(nsURI, _loginBody);

            //Reading the content back from the response. This could contain an error message but for
            //simplicity, this example does trap for that.
            string _responseJson = await _msg.Content.ReadAsStringAsync();

            //convert the response json into a plain old CLR object (class)
            ReturnInfo returnJsonBody = Newtonsoft.Json.JsonConvert.DeserializeObject <ReturnInfo>(_responseJson);

            //Print out information returned to the user
            Console.WriteLine("Return value from Netscaler CPX authentication");
            Console.WriteLine(_responseJson);
        }
Exemple #49
0
        public void TestArbitrary()
        {
            AutoResetEvent are       = new AutoResetEvent(false);
            var            client    = new AustinHarris.JsonRpc.JsonRpcClient(remoteUri);
            var            arbitrary = new Newtonsoft.Json.Linq.JObject();
            JObject        r         = null;
            Exception      e         = null;

            for (int i = 0; i < 10; i++)
            {
                arbitrary[getPrintableString(10)]     = getPrintableString(20);
                arbitrary[getNonPrintableString(10)]  = getNonPrintableString(20);
                arbitrary[getExtendedAsciiString(10)] = getExtendedAsciiString(20);
            }

            var myObs = client.Invoke <Newtonsoft.Json.Linq.JObject>("testArbitraryJObject", arbitrary, Scheduler.TaskPool);

            using (myObs.Subscribe(
                       onNext: (jo) =>
            {
                r = jo.Result;
            },
                       onError:   _ =>
            {
                e = _;
            },
                       onCompleted: () => are.Set()
                       ))
            {
                are.WaitOne();
            };


            Assert.IsTrue(r.ToString() == arbitrary.ToString());
            Assert.IsTrue(e == null);
        }
Exemple #50
0
        protected override void MessageReceivedHandler(Newtonsoft.Json.Linq.JObject jsonMessage)
        {
            if (_manager.Config.Filters != null)
            {
                ApplyFilters(jsonMessage);
            }

            var message = jsonMessage.ToString();

            LogManager.GetCurrentClassLogger().Trace(message);

            lock (_locker)
            {
                if (_jsonQueue.Count >= _maxQueueSize)
                {
                    // If we've exceeded our queue size, and we're supposed to throw out the oldest objects first,
                    // then remove as many as necessary to get us under our limit
                    if (_queueOverflowDiscardOldest)
                    {
                        LogManager.GetCurrentClassLogger()
                        .Warn("Overflow discarding oldest {0} messages", _jsonQueue.Count - _maxQueueSize + 1);

                        _jsonQueue.RemoveRange(0, (_jsonQueue.Count - _maxQueueSize) + 1);
                    }
                    // Otherwise we're in a "discard newest" mode, and this is the newest message, so just ignore it
                    else
                    {
                        LogManager.GetCurrentClassLogger()
                        .Warn("Overflow discarding newest message: {0}", message);

                        return;
                    }
                }
                _jsonQueue.Add(jsonMessage);
            }
        }
Exemple #51
0
        void DoCallTran(ThinNeo.Transaction tx)
        {
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "sendrawtransaction";
            var _params = new Newtonsoft.Json.Linq.JArray();

            var data = tx.GetRawData();

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

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

            Console.WriteLine(info);

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

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

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

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

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

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

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

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

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

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

            tx.AddWitness(data, pubkey, addres);

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

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

            var vdata = tx.GetRawData();

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

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

            ret.txid = this_txid.ToString();
            ret.rsp  = info;
            this.list2.Items.Add(ret);
        }
Exemple #53
0
        internal static NIMIMMessage CreateMessage(Newtonsoft.Json.Linq.JObject token)
        {
            if (!token.HasValues || token.Type != Newtonsoft.Json.Linq.JTokenType.Object)
            {
                return(null);
            }
            var msgTypeToken = token.SelectToken(NIMIMMessage.MessageTypePath);

            if (msgTypeToken == null)
            {
                throw new ArgumentException("message type must be seted:" + token.ToString(Formatting.None));
            }
            var          msgType = msgTypeToken.ToObject <NIMMessageType>();
            NIMIMMessage message = null;

            ConvertAttachStringToObject(token);
            var msgJsonValue = token.ToString(Formatting.None);

            switch (msgType)
            {
            case NIMMessageType.kNIMMessageTypeAudio:
                message = NimUtility.Json.JsonParser.Deserialize <NIMAudioMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeFile:
                message = NimUtility.Json.JsonParser.Deserialize <NIMFileMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeImage:
                message = NimUtility.Json.JsonParser.Deserialize <NIMImageMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeLocation:
                message = NimUtility.Json.JsonParser.Deserialize <NIMLocationMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeText:
                message = NimUtility.Json.JsonParser.Deserialize <NIMTextMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeVideo:
                message = NimUtility.Json.JsonParser.Deserialize <NIMVideoMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeNotification:
                message = NimUtility.Json.JsonParser.Deserialize <NIMTeamNotificationMessage>(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeCustom:
                message = NimUtility.Json.JsonParser.Deserialize <NIMCustomMessage <object> >(msgJsonValue);
                break;

            case NIMMessageType.kNIMMessageTypeTips:
                ConvertAttachObjectToString(token);
                msgJsonValue = token.ToString(Formatting.None);
                message      = NimUtility.Json.JsonParser.Deserialize <NIMTipMessage>(msgJsonValue);
                break;

#if NIMAPI_UNDER_WIN_DESKTOP_ONLY
            case NIMMessageType.kNIMMessageTypeRobot:
                message = Robot.ResponseMessage.Deserialize(token);
                break;
#endif
            default:
                message = NimUtility.Json.JsonParser.Deserialize <NIMUnknownMessage>(msgJsonValue);
                ((NIMUnknownMessage)message).RawMessage = token.ToString(Formatting.None);
                break;
            }
            return(message);
        }
Exemple #54
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;
                }));
            }
        }
Exemple #55
0
 public override string ToString()
 {
     return(data.ToString());
 }
Exemple #56
0
        private HtmlGenericControl GenerateTestRunSummarySection()
        {
            HtmlGenericControl divTestRunSummary = new HtmlGenericControl("div");

            divTestRunSummary.ID = "testRunSummary";

            //List<XElement> tests = new List<XElement>(_xDoc.Document.XPathSelectElements(ReportElements.ReportTag + "/" + ReportElements.TestTag));

            //divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<h1 id=\"testRunName\" class=\"summaryTitle\"><span style=\"font-weight: bold;\">Test Run Name: </span><span id=\"testRunNameVal\"></span></h1>"))); // , this.SuiteName
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunStartTime\" class=\"summaryData\"><span style=\"font-weight: bold;\">Start Time: </span><span id=\"testRunStartTimeVal\"></span></p>")));                      // , String.Format("{0} ({1})", startTime.ToDateTimeUtc().ToLocalTime().ToString("ddd, MMM dd, yyyy HH:mm:ss zzz"), System.TimeZoneInfo.Local.StandardName)
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunEndTime\" class=\"summaryData\"><span style=\"font-weight: bold;\">End Time: </span><span id=\"testRunEndTimeVal\"></span></p>")));                            // , String.Format("{0} ({1})", startTime.ToDateTimeUtc().ToLocalTime().ToString("ddd, MMM dd, yyyy HH:mm:ss zzz"), System.TimeZoneInfo.Local.StandardName)
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunDuration\" class=\"summaryData\"><span style=\"font-weight: bold;\">Duration: </span><span id=\"testRunDurationVal\"></span></p>")));                          // , duration.ToString(@"hh\:mm\:ss\.fff")
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofTests\" class=\"summaryData\"><span style=\"font-weight: bold;\">Number of Tests: </span><span id=\"testRunNumofTestsVal\"></span></p>")));               // , total
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofPass\" class=\"summaryData stepPass\"><span style=\"font-weight: bold;\">Total Pass: </span><span id=\"testRunNumofPassVal\"></span></p>")));             // , passed
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofWarning\" class=\"summaryData stepWarning\"><span style=\"font-weight: bold;\">Total Warning: </span><span id=\"testRunNumofWarningVal\"></span></p>"))); // , warning
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofFail\" class=\"summaryData stepFail\"><span style=\"font-weight: bold;\">Total Fail: </span><span id=\"testRunNumofFailVal\"></span></p>")));             // , failed

            Newtonsoft.Json.Linq.JObject jsonObj = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(_testsSummary));
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<input name='testRunSummaryObj' type='hidden' value='{0}' />", jsonObj.ToString())));

            return(divTestRunSummary);
        }
Exemple #57
0
 public bool WriteData(string collection, Newtonsoft.Json.Linq.JObject data)
 {
     try
     {
         UpdateCommonData(data);
         data[CommonConst.CommonField.CREATED_DATA_DATE_TIME] = CommonUtility.GetUnixTimestamp(DateTime.Now);
         data[CommonConst.CommonField.UPDATED_DATE_TIME]      = CommonUtility.GetUnixTimestamp(DateTime.Now);
         data[CommonConst.CommonField.CREATED_BY]             = GetUserId();
         var dbcollection = _mongoDataBase.GetCollection <BsonDocument>(collection);
         MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(data.ToString());
         dbcollection.InsertOne(document);
         return(true);
     }
     catch (System.Exception ex)
     {
         if (ex.Message.Contains("duplicate key error"))
         {
             throw new DuplicateDBIDException((int)ErrorCode.DB.DUPLICATE_ID, ErrorCode.DB.DUPLICATE_ID.ToString(), ex);
         }
         else
         {
             throw;
         }
     }
 }
Exemple #58
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);
            }
        }
    /**
     * 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);
    }
        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;
            //}
        }