Ejemplo n.º 1
1
 private void Start()
 {
     HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlUserId + "/" + PlayerPrefs.GetString("UserId") + "?access_token=" + PlayerPrefs.GetString("token")), HTTPMethods.Get, OnRequestFinished);
     // Debug.Log(APIUrl.UrlUserId + "/" + PlayerPrefs.GetString("UserId") + "?access_token=" + PlayerPrefs.GetString("token"));
     //  request.AddField("id", PlayerPrefs.GetString("UserId"));
     request.Send();
 }
Ejemplo n.º 2
1
    public IEnumerator GetImage(System.Action<Image> callback, System.Action<string> errorCallback)
    {
        if (imageList.Images.Count == 0)
        {
            // no images, get new
            yield return StartCoroutine(GetImages(errorCallback));
        }

        if (imageList.Images.Count == 0)
        {
            yield break;
        }

        int index = Random.Range(0, imageList.Images.Count - 1);
        Image i = imageList.Images[index];

        HTTPRequest req = new HTTPRequest(new System.Uri(i.Url));
        req.Send();
        yield return StartCoroutine(req);

        if(req.Response==null || !req.Response.IsSuccess)
        {
            errorCallback("Get Image Error");
            yield break;
        }

        imageList.Images.RemoveAt(index);

        i.Tex = req.Response.DataAsTexture2D;
        callback(i);
        yield return null;
    }
	void onAuthenticationFinished(HTTPRequest req, HTTPResponse res) {
		JsonReader json = new JsonReader (res.DataAsText);
		json.SkipNonMembers = true;
		// deserialize
		Token token = JsonMapper.ToObject<Token> (json);
		// authentication correct
		if (token != null) {
			if (token.success) {
				// save to player preferences
				PlayerPrefs.SetString ("token", token.token);
				PlayerPrefs.SetString ("username", token.username);
				PlayerPrefs.Save();
				// when we finish the authentication process, load the main menu
				utils.loadScene("MainMenu");
			}
			else {
				Debug.Log(token.message);
				_dispatcher.Dispatch("show_error_register_login");
			}
		}
		// authentication erroneous, show error message
		else {
			//TODO: show error message
		}
	}
Ejemplo n.º 4
0
	public void sendAction() {

		GetComponent<Animator>().Play("Click");

		if (buttonType == FLOOR_BUTTON_TYPE.YES || buttonType == FLOOR_BUTTON_TYPE.NO) {

			GameObject.Find("Debug Text").GetComponent<Text>().text += "Setting Position \n";

			HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/action"), HTTPMethods.Put, actionSentCallback);

			JSONClass data = new JSONClass();

			data["value"] = ((int)buttonType).ToString();

			request.AddHeader("Content-Type", "application/json");
			//request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
			request.RawData = Encoding.UTF8.GetBytes(data.ToString());
			request.Send();
		} else {

			HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/dlswitch"), HTTPMethods.Put, actionSentCallback);

			JSONClass data = new JSONClass();

			data["value"] = (dlSwitch).ToString();

			request.AddHeader("Content-Type", "application/json");
			//request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
			request.RawData = Encoding.UTF8.GetBytes(data.ToString());
			request.Send();
		}



	}
Ejemplo n.º 5
0
 public override void PrepareRequest(HTTPRequest request)
 {
     if (Form.headers.ContainsKey("Content-Type"))
         request.SetHeader("Content-Type", Form.headers["Content-Type"] as string);
     else
         request.SetHeader("Content-Type", "application/x-www-form-urlencoded");
 }
Ejemplo n.º 6
0
 public  SessionInfo()
 {
     Ignore = false;
     BypassServerRequest = false;
     Response = new HTTPResponse();
     Request = new HTTPRequest();
 }
Ejemplo n.º 7
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            if (request.path.StartsWith(PAGE_PREFIX))
            {
                dataRates.addUpLinkPoint(System.DateTime.Now, request.path.Length);

                try
                {
                    dataSources.vessel = FlightGlobals.ActiveVessel;
                    vesselChangeDetector.update(FlightGlobals.ActiveVessel);
                }
                catch (Exception e)
                {
                    PluginLogger.debug(e.Message + " "  + e.StackTrace);
                }

                dataRates.addDownLinkPoint(
                    System.DateTime.Now,
                    ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                        argumentsParse(request.path.Remove(0,
                            request.path.IndexOf(ARGUMENTS_START) + 1),
                            dataSources)
                   )));

                return true;
            }

            return false;
        }
Ejemplo n.º 8
0
 public void HandleRequest(HTTPRequest request, HTTPResponse response)
 {
     if (_redirectionType == WoopsaRedirectionType.Temporary)
         response.SetStatusCode((int)HTTPStatusCode.TemporaryRedirect, "Temporary redirect");
     else if (_redirectionType == WoopsaRedirectionType.Permanent)
         response.SetStatusCode((int)HTTPStatusCode.Moved, "Permanent redirection");
     response.SetHeader("Location", _targetLocation);
 }
Ejemplo n.º 9
0
        internal WebSocketResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache)
            : base(request, stream, isStreamed, isFromCache)
        {
            base.IsClosedManually = true;

            closed = false;
            MaxFragmentSize = UInt16.MaxValue / 2;
        }
	void processGameEnd(HTTPRequest req, HTTPResponse res) {
		// deserialize json
		GameModel game = JsonMapper.ToObject<GameModel> (res.DataAsText);
		// update game
		if (!string.IsNullOrEmpty(((GameModel)game)._id)) {
			_dispatcher.Dispatch("update_game", game);
		}
	}
 void doAuthentication(string username, string password)
 {
     // if there is no token stored, negotiate a new one
     HTTPRequest req = new HTTPRequest (new System.Uri (Properties.API + "/authenticate"), HTTPMethods.Post, onAuthenticationFinished);
     req.AddField ("username", username);
     req.AddField ("password", password);
     req.Send ();
 }
	void endAPICall(HTTPRequest req, HTTPResponse res) {
		// deserialize json
		question = JsonMapper.ToObject<QuestionModel> (res.DataAsText);
		// save questionId
		PlayerPrefs.SetString ("questionId", question._id);
		// end spinning
		callingAPI = false;
	}
        void OnAuthRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            AuthRequest = null;
            string failReason = string.Empty;

            switch (req.State)
            {
                // The request finished without any problem.
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess)
                    {
                        Cookie = resp.Cookies != null ? resp.Cookies.Find(c => c.Name.Equals(".ASPXAUTH")) : null;

                        if (Cookie != null)
                        {
                            HTTPManager.Logger.Information("CookieAuthentication", "Auth. Cookie found!");

                            if (OnAuthenticationSucceded != null)
                                OnAuthenticationSucceded(this);

                            // return now, all other paths are authentication failures
                            return;
                        }
                        else
                            HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Auth. Cookie NOT found!");
                    }
                    else
                        HTTPManager.Logger.Warning("CookieAuthentication", failReason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                        resp.StatusCode,
                                                        resp.Message,
                                                        resp.DataAsText));
                    break;

                // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
                case HTTPRequestStates.Error:
                    HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
                    break;

                // The request aborted, initiated by the user.
                case HTTPRequestStates.Aborted:
                    HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Request Aborted!");
                    break;

                // Ceonnecting to the server is timed out.
                case HTTPRequestStates.ConnectionTimedOut:
                    HTTPManager.Logger.Error("CookieAuthentication", failReason = "Connection Timed Out!");
                    break;

                // The request didn't finished in the given time.
                case HTTPRequestStates.TimedOut:
                    HTTPManager.Logger.Error("CookieAuthentication", failReason = "Processing the request Timed Out!");
                    break;
            }

            if (OnAuthenticationFailed != null)
                OnAuthenticationFailed(this, failReason);
        }
Ejemplo n.º 14
0
    private void OnClick()
    {
        HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlLogin), HTTPMethods.Post, OnRequestFinished);
        request.AddField("username", username.text);
        request.AddField("password", password.text);
        request.Send();

        //SceneManager.LoadScene(1);
    }
Ejemplo n.º 15
0
    private void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

        for (int i = 0; i < json.Count; i++)
        {
            itemlist.Add(new Item(
                 json[i]["code"]
                 , json[i]["name"]
                 , json[i]["damage"]
                 , json[i]["price"]
                 , json[i]["avatar"]
                 , json[i]["itemCategoryId"]
                 , json[i]["id"]
                 , json[i]["categoryId"]
                 ));
            //kiem tra xem sung da mua chua
            itemlist [i].bought = 0;
            //Debug.Log ("so sanh item ; " + json [i] ["id"]);
            for(int k = 0; k<GetUserId.itemid.Count; k++){
            //	Debug.Log ("so sanh voi :" + GetUserId.itemid [k]+ "va ;"+ json[i]["id"]);
                if (json [i] ["id"].ToString().Trim('"').Equals( GetUserId.itemid [k].ToString())) {
                    itemlist [i].bought = 1;
                    Debug.Log ("trung nhau giua ;"+ GetUserId.itemid[k] +"va :"+ json[i]["name"]);

                }
            }
            GameObject bullet3;
            if (itemlist [i].bought == 1) {
                 bullet3 = (GameObject)Instantiate (itemprefab2, itemPo [i].transform.position, Quaternion.identity);
            } else {
                 bullet3 = (GameObject)Instantiate (itemprefab1, itemPo [i].transform.position, Quaternion.identity);
            }

            Transform[] allChildren = bullet3.transform.GetComponentsInChildren<Transform>();
            foreach (Transform t in allChildren)
            {
                if (t != null && t.gameObject.name == "Wp")
                {

                    new HTTPRequest(new Uri(json[i]["avatar"]), (request, res)
                    =>
                    {
                        var texture = new Texture2D(0, 0);
                      //  Debug.Log("red.data = "+ res);
                        texture.LoadImage(res.Data);
                      t.GetComponent<SpriteRenderer>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    }
                    ).Send();
                }
            }
            bullet3.transform.SetParent(GameObject.Find("Weapons").transform);
            bullet3.transform.position = itemPo[i].transform.position;
            bullet3.transform.localScale = new Vector3 (0.9f, 0.9f, 0.9f);
        }
    }
Ejemplo n.º 16
0
    private void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

           // Debug.Log(response.DataAsText);
        for (int i = 0; i < json ["item"].Count; i++) {
            itemid.Add(json["item"][i]);
            //Debug.Log ("item la " + itemid[i]);
        }
    }
        public void StartAuthentication()
        {
            AuthRequest = new HTTPRequest(AuthUri, HTTPMethods.Post, OnAuthRequestFinished);

            // Setup the form
            AuthRequest.AddField("userName", UserName);
            AuthRequest.AddField("Password", Password); // not used in the sample
            AuthRequest.AddField("roles", UserRoles);

            AuthRequest.Send();
        }
Ejemplo n.º 18
0
	void responseReady(HTTPRequest req, HTTPResponse res) {
		responseRdy = true;
		// deserialize json
		game = JsonMapper.ToObject<GameModel> (res.DataAsText);
		// send analytics
		if (!correctAnswer) {
			GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus.GAProgressionStatusComplete, "match", "turn_" + (game.turn - 1));
		}
		// call process response to sync with wait
		processResponse ();
	}
Ejemplo n.º 19
0
 /// <summary>
 /// Create a new HTTP response.
 /// </summary>
 /// <param name="HTTPRequest">The HTTP request for this response.</param>
 /// <param name="HTTPStatusCode">A HTTP status code</param>
 public HTTPResponseBuilder(HTTPRequest     HTTPRequest,
                            HTTPStatusCode  HTTPStatusCode = null)
 {
     this._HTTPRequest       = HTTPRequest;
     this._HTTPStatusCode    = HTTPStatusCode;
     this._Timestamp         = DateTime.Now;
     this.ProtocolName       = "HTTP";
     this.ProtocolVersion    = new HTTPVersion(1, 1);
     this.CancellationToken  = HTTPRequest?.CancellationToken ?? new CancellationTokenSource().Token;
     base.EventTrackingId    = HTTPRequest?.EventTrackingId   ?? EventTracking_Id.New;
 }
        public override void Stop()
        {
            HTTPManager.Heartbeats.Unsubscribe(this);

            if (pollRequest != null)
            {
                pollRequest.Abort();
                pollRequest = null;
            }

            // Should we abort the send requests in the sendRequestQueue?
        }
 // get game info from API
 void getGame()
 {
     // get all the games
     HTTPRequest request = new HTTPRequest(new System.Uri(Properties.API + "/game/" + _gameId), (HTTPRequest req, HTTPResponse res) => {
         // deserialize json
         GameModel games = JsonMapper.ToObject<GameModel> (res.DataAsText);
         // build scene
         buildScene(games);
     });
     request.AddField ("token", PlayerPrefs.GetString ("token"));
     request.Send ();
 }
Ejemplo n.º 22
0
 public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
 {
     if (!KSP.IO.FileInfo.CreateForType<TelemachusDataLink>(INDEX_PAGE).Exists)
     {
         throw new PageNotFoundResponsePage("Unable to find the Telemachus index page. Is it installed in the PluginData folder?");
     }
     else
     {
         throw new PageNotFoundResponsePage(
             "Did you mean to visit the <a href=\"/" + INDEX_PAGE + "\">index page</a>?");
     }
 }
 // create a new game
 public void createGame()
 {
     string challenger = PlayerPrefs.GetString("username");
     string challenged = (challenger == "berni") ? "gemmins" : "berni";
     Debug.Log (PlayerPrefs.GetString("token"));
     HTTPRequest request = new HTTPRequest (new System.Uri (Properties.API + "/game"), HTTPMethods.Post, (HTTPRequest req, HTTPResponse res) => {
         //TODO: jump to the new game
     });
     request.AddField ("challenger", challenger);
     request.AddField ("challenged", challenged);
     request.AddField ("token", PlayerPrefs.GetString("token"));
     request.Send ();
 }
Ejemplo n.º 24
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            DataSources dataSources = new DataSources();

            if (request.path.StartsWith(PAGE_PREFIX))
            {
                if (request.requestType == HTTPRequest.GET)
                {
                    dataRates.addUpLinkPoint(System.DateTime.Now, request.path.Length * UpLinkDownLinkRate.BITS_PER_BYTE);
                }
                else if (request.requestType == HTTPRequest.POST)
                {
                    dataRates.addUpLinkPoint(System.DateTime.Now, request.content.Length * UpLinkDownLinkRate.BITS_PER_BYTE);
                }

                try
                {
                    dataSources.vessel = kspAPI.getVessel();
                }
                catch (Exception e)
                {
                    PluginLogger.debug(e.Message + " " + e.StackTrace);
                }

                if (request.requestType == HTTPRequest.GET)
                {
                    dataRates.addDownLinkPoint(
                        System.DateTime.Now,
                        ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                            argumentsParse(request.path.Remove(0,
                                request.path.IndexOf(ARGUMENTS_START) + 1),
                                dataSources)
                        )) * UpLinkDownLinkRate.BITS_PER_BYTE);
                }
                else if (request.requestType == HTTPRequest.POST)
                {
                    dataRates.addDownLinkPoint(
                        System.DateTime.Now,
                        ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                            argumentsParse(request.content,
                                dataSources)
                        )) * UpLinkDownLinkRate.BITS_PER_BYTE);
                }

                return true;
            }

            return false;
        }
	void questionReady(HTTPRequest req, HTTPResponse res) {
		float delay = ((Time.time - startTime) < (Properties.starQuestionDelay - Properties.delayQuestionStart)) ? Properties.starQuestionDelay : Properties.delayQuestionStart;
		// parse response
		question = JsonMapper.ToObject<QuestionModel> (res.DataAsText);
		// save questionId
		PlayerPrefs.SetString ("questionId", question._id);
		// deay action and launch question
		Utils.delayAction (this, () => {
			// dispatch event to start question
			_dispatcher.Dispatch ("question_loaded", question);
			// fadeout panel
			Utils.fadeOutPanel (this, panel, Properties.starQuestionFadeInOutDuration, executeQuestion);
		}, 
		delay);
	}
Ejemplo n.º 26
0
  IEnumerator DemoFormPost()
  {
    _test = "DemoFormPost";

    HTTPRequest request = new HTTPRequest();

    request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123").
      SetContentString("foo=bar&cafe=babe", "application/octet-stream").
      Post();

    using (_client = new HTTPClient(request))
    {
      yield return StartCoroutine(_client.WaitUntilDone());
      DebugAll(_client);
    }
  }
Ejemplo n.º 27
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            if (request.path.StartsWith("/server"))
            {
                try
                {
                    cc.Send(new OKResponsePage("Server Running.").ToString());
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// Polling transport specific connection logic. It's a regular GET request to the /connect path.
        /// </summary>
        public override void Connect()
        {
            HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Open Request");

            // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly
            if (this.State != TransportStates.Reconnecting)
                this.State = TransportStates.Connecting;

            RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect;

            var request = new HTTPRequest(Connection.BuildUri(requestType, this), HTTPMethods.Get, true, true, OnConnectRequestFinished);

            Connection.PrepareRequest(request, requestType);

            request.Send();
        }
Ejemplo n.º 29
0
        public static void StartHTTPFlood()
        {
            tFloodingThread = new Thread[iThreads];
            tFloodingJob = new ThreadStart[iThreads];
            hRequestClass = new HTTPRequest[iThreads];

            if (!sFHost.StartsWith("http://")) { sFHost = "http://" + sFHost; }

            for (int i = 0; i < iThreads; i++)
            {
                hRequestClass[i] = new HTTPRequest(sFHost);
                tFloodingJob[i] = new ThreadStart(hRequestClass[i].Send);
                tFloodingThread[i] = new Thread(tFloodingJob[i]);
                tFloodingThread[i].Start();
            }
        }
Ejemplo n.º 30
0
    public void RequestConfig() {
      if(_requestingConfig) {
        return;
      }
      _requestingConfig = true;
      string configRequestUrl = Settings.mediationEndpoint + "/v1/games/" + Engine.Instance.AppId + "/config";
      //string configRequestUrl = Settings.serverEndpoint + "/testConfig.json";
      HTTPRequest request = new HTTPRequest("POST", configRequestUrl);
      request.addHeader("Content-Type", "application/json");
      if(configId != null) {
        request.addHeader("If-None-Match", configId);
      }
      request.setPayload(DeviceInfo.getJson());

      Utils.LogDebug("Requesting new config from " + configRequestUrl);
      request.execute(HandleConfigResponse);
    }
Ejemplo n.º 31
0
        public void SendSMS(PlainSMS sms)
        {
            try
            {
                //  List<SMS> caches = new List<SMS>();

                string post = "";


                string content = "";
                if (SignaturePos == "0")
                {
                    //签名在前
                    content = sms.Signature + sms.Content;
                }
                else
                {
                    //签名在后
                    content = sms.Content + sms.Signature;
                }
                post = "action=send&userid=" + userId + "&account=" + account + "&password="******"&mobile=" + sms.Numbers + "&content=" + content + "&sendTime=&extno=" + SrcID + sms.SPNumber;
                // MessageHelper.Instance.WirteTest("发送字符串: " + post);
                string t = HTTPRequest.PostWebRequest(sendUrl, post, Encoding.UTF8);
                //string t = "";
                MessageHelper.Instance.WirteTest("提交返回原始内容: " + t);
                //<? xml version = "1.0" encoding = "utf-8" ?>
                //< returnsms >
                //< returnstatus > status </ returnstatus > ----------返回状态值:成功返回Success 失败返回:Faild
                //<message> message</ message > ----------返回信息:见下表
                //<remainpoint> remainpoint</ remainpoint > ----------返回余额
                //< taskID > taskID </ taskID > -----------返回本次任务的序列ID
                //< successCounts > successCounts </ successCounts > --成功短信数:当成功后返回提交成功短信数
                //</ returnsms >

                bool        ok    = true;
                string      rmsg  = "";
                string      msgid = "";
                XmlDocument doc   = new XmlDocument();
                doc.LoadXml(t);
                XmlElement root = null;
                root = doc.DocumentElement;
                XmlNodeList listNodes = root.ChildNodes;
                foreach (XmlNode node in listNodes)
                {
                    switch (node.Name)
                    {
                    case "returnstatus":
                        ok = (node.InnerText == "Success") ? true : false;
                        break;

                    case "message":
                        if (node.InnerText == "ok")
                        {
                            rmsg = "短信提交成功.";
                        }
                        else
                        {
                            rmsg = node.InnerText;
                        }
                        break;

                    case "remainpoint":
                        break;

                    case "taskID":
                        msgid = node.InnerText;
                        break;

                    case "successCounts":
                        break;
                    }
                }


                int r = 1;//原来默认0 ,应为1  by lmw  1 代表已发送
                if (!ok)
                {
                    // r = 101;
                    r = 99;//提交失败 错误码应该在100以内吧   by lmw
                    if (string.IsNullOrWhiteSpace(msgid) || msgid == "0")
                    {
                        msgid = System.Guid.NewGuid().ToString();
                    }
                }



                int i = 0;
                foreach (string num in sms.Numbers.Split(','))
                {
                    PlainSMS s = PlainSMS.GetPlainSMSWithOneNumber(sms, num);
                    i++;
                    SendEventArgs se = new SendEventArgs(s, msgid + i.ToString().PadLeft(5, '0'), ok, (ushort)(2000 + r), rmsg, 1, 1);
                    if (SendEvent != null)
                    {
                        SendEvent(this, se);
                    }
                    //string result = JsonSerialize.Instance.Serialize<SendEventArgs>(se);
                    //IService.ServiceProxy.Instance.WriteTest("短信发送结果:" + result);
                    ExSendEventArgs ese = new ExSendEventArgs(se);
                    if (ok)
                    {
                        lock (sendslocker)
                        {
                            sends.Add(se.SerialNumber, ese);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageHelper.Instance.WirteError(ex.ToString());
                LogClient.LogHelper.LogInfo("OPWO", "SendSMS Error ->", ex.Message);
            }
        }
Ejemplo n.º 32
0
        public void SendSMS(SMSModel.SMS sms)
        {
            try
            {
                string post = "";
                post = "action=send&userid=" + userId + "&account=" + account + "&password="******"&mobile=" + string.Join(",", sms.Number) + "&content=" + sms.Content + sms.Signature + "&sendTime=&extno=" + scrId + sms.SPNumber;
                //   Console.WriteLine("发送字符串 " + post);
                string t = HTTPRequest.PostWebRequest(sendUrl, post, Encoding.UTF8);
                //<? xml version = "1.0" encoding = "utf-8" ?>
                //< returnsms >
                //< returnstatus > status </ returnstatus > ----------返回状态值:成功返回Success 失败返回:Faild
                //<message> message</ message > ----------返回信息:见下表
                //<remainpoint> remainpoint</ remainpoint > ----------返回余额
                //< taskID > taskID </ taskID > -----------返回本次任务的序列ID
                //< successCounts > successCounts </ successCounts > --成功短信数:当成功后返回提交成功短信数
                //</ returnsms >
                // Console.WriteLine("发送返回消息 " + t);
                bool        ok    = true;
                string      rmsg  = "";
                string      msgid = "";
                XmlDocument doc   = new XmlDocument();
                doc.LoadXml(t);
                XmlElement root = null;
                root = doc.DocumentElement;
                XmlNodeList listNodes = root.ChildNodes;
                foreach (XmlNode node in listNodes)
                {
                    switch (node.Name)
                    {
                    case "returnstatus":
                        ok = (node.InnerText == "Success") ? true : false;
                        break;

                    case "message":
                        if (node.InnerText == "OK")
                        {
                            rmsg = "短信提交成功.";
                        }
                        else
                        {
                            rmsg = node.InnerText;
                        }
                        break;

                    case "remainpoint":
                        break;

                    case "taskID":
                        msgid = node.InnerText;
                        break;

                    case "successCounts":
                        break;
                    }
                }
                int r = 1;
                if (!ok)
                {
                    r = 99;
                }
                int i = 0;
                MessageHelper.Instance.WirteTest("短信提交一次  " + string.Join(",", sms.Number) + "         " + rmsg);
                foreach (string num in sms.Number)
                {
                    SMS s = new SMS();

                    s.Account = sms.Account;
                    s.Audit   = sms.Audit;
                    s.Channel = sms.Channel;
                    s.Content = sms.Content;
                    s.Filter  = sms.Filter;
                    s.Level   = sms.Level;
                    s.Number  = new List <string> {
                        num
                    };
                    s.SendTime     = sms.SendTime;
                    s.SerialNumber = sms.SerialNumber;
                    s.StatusReport = sms.StatusReport;
                    s.Signature    = sms.Signature;
                    s.SPNumber     = sms.SPNumber;
                    s.WapURL       = sms.WapURL;
                    i++;
                    SendEventArgs   se  = new SendEventArgs(s, msgid + i.ToString().PadLeft(5, '0'), ok, (ushort)(2000 + r), rmsg, 1, 1);
                    ExSendEventArgs ese = new ExSendEventArgs(se);
                    if (SendEvent != null)
                    {
                        SendEvent(this, se);
                    }
                    if (ok)
                    {
                        lock (locker)
                        {
                            sends.Add(se.Serial, ese);
                        }
                    }
                }
            }


            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                LogClient.LogHelper.LogInfo("ZS3WG", "SendSMS Error ->", ex.Message);
            }
        }
Ejemplo n.º 33
0
        private void OnClientConnect(System.IAsyncResult result)
        {
            Log.Write("Incoming client connecting");

            Socket client;

            try
            {
                client = listener.EndAccept(result);
            }
            catch (System.Exception e)
            {
                Log.WriteError("Exception when accepting incoming connection: " + e);
                return;
            }

            try
            {
                listener.BeginAccept(new System.AsyncCallback(OnClientConnect), listener);
            }
            catch (System.Exception e)
            {
                Log.WriteError("Exception when starting new accept process: " + e);
            }

            try
            {
                // Disable the Nagle Algorithm for this tcp socket.
                client.NoDelay = true;

                // Set the receive buffer size to 8k
                client.ReceiveBufferSize = 8192;

                // Set the timeout for synchronous receive methods
                //client.ReceiveTimeout = 5000;

                // Set the send buffer size to 8k.
                client.SendBufferSize = 8192;

                // Set the timeout for synchronous send methods
                //client.SendTimeout = 5000;

                // Set the Time To Live (TTL) to 42 router hops.
                client.Ttl = 42;

                bool keepAlive = false;

                int requestCount = 0;

                using (var stream = new NetworkStream(client))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        using (var writer = new BinaryWriter(stream))
                        {
                            {
                                do
                                {
                                    var         lines   = new List <string>();
                                    HTTPRequest request = null;

                                    var  line = new StringBuilder();
                                    char prevChar;
                                    char currentChar = '\0';
                                    while (true)
                                    {
                                        prevChar    = currentChar;
                                        currentChar = (char)reader.ReadByte();

                                        if (currentChar == '\n' && prevChar == '\r')
                                        {
                                            if (line.Length == 0)
                                            {
                                                request = new HTTPRequest();
                                                break;
                                            }

                                            var temp = line.ToString();
                                            Log.Write(temp, Log.Level.Debug1);

                                            if (temp.Contains("\0"))
                                            {
                                                throw new Exception("Null Byte Injection detected");
                                            }

                                            lines.Add(temp);
                                            line.Length = 0;
                                        }
                                        else
                                        if (currentChar != '\r' && currentChar != '\n')
                                        {
                                            line.Append(currentChar);
                                        }
                                    }

                                    bool isWebSocket = false;

                                    // parse headers
                                    if (request != null)
                                    {
                                        for (int i = 1; i < lines.Count; i++)
                                        {
                                            var temp = lines[i].Split(':');
                                            if (temp.Length >= 2)
                                            {
                                                var key = temp[0];
                                                var val = temp[1].TrimStart();

                                                request.headers[key] = val;

                                                if (key.Equals("Content-Length", StringComparison.InvariantCultureIgnoreCase))
                                                {
                                                    int contentLength = int.Parse(val);
                                                    request.bytes = reader.ReadBytes(contentLength);
                                                }
                                                else
                                                if (key.Equals("Upgrade", StringComparison.InvariantCultureIgnoreCase))
                                                {
                                                    isWebSocket = true;
                                                }
                                            }
                                        }
                                    }

                                    if (request != null)
                                    {
                                        var s = lines[0].Split(' ');

                                        if (s.Length == 3)
                                        {
                                            switch (s[0].ToUpperInvariant())
                                            {
                                            case "GET": request.method = HTTPRequest.Method.Get; break;

                                            case "POST": request.method = HTTPRequest.Method.Post; break;

                                            case "HEAD": request.method = HTTPRequest.Method.Head; break;

                                            case "PUT": request.method = HTTPRequest.Method.Put; break;

                                            case "DELETE": request.method = HTTPRequest.Method.Delete; break;

                                            default: throw new Exception("Invalid HTTP method: " + s[0]);
                                            }

                                            request.version = s[2];

                                            var path = s[1].Split('?');
                                            request.path = path[0];
                                            request.url  = s[1];

                                            Log.Write(request.method.ToString() + " " + s[1], Log.Level.Debug1);

                                            if (isWebSocket)
                                            {
                                                Action <WebSocket> handler        = null;
                                                string             targetProtocol = null;

                                                var protocolHeader = "Sec-WebSocket-Protocol";

                                                if (request.headers.ContainsKey(protocolHeader))
                                                {
                                                    var protocols = request.headers[protocolHeader].Split(',').Select(x => x.Trim());
                                                    foreach (var protocol in protocols)
                                                    {
                                                        var key = MakeWebSocketKeyPair(protocol, request.path);
                                                        if (_websocketsHandlers.ContainsKey(key))
                                                        {
                                                            targetProtocol = protocol;
                                                            handler        = _websocketsHandlers[key];
                                                            break;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    targetProtocol = null;
                                                    var key = MakeWebSocketKeyPair(targetProtocol, request.path);
                                                    if (_websocketsHandlers.ContainsKey(key))
                                                    {
                                                        handler = _websocketsHandlers[key];
                                                    }
                                                }

                                                if (handler != null)
                                                {
                                                    var key = request.headers["Sec-WebSocket-Key"];
                                                    key = GenerateWebSocketKey(key);

                                                    var sb = new StringBuilder();
                                                    sb.Append("HTTP/1.1 101 Switching Protocols\r\n");
                                                    sb.Append("Upgrade: websocket\r\n");
                                                    sb.Append("Connection: Upgrade\r\n");
                                                    sb.Append($"Sec-WebSocket-Accept: {key}\r\n");
                                                    if (targetProtocol != null)
                                                    {
                                                        sb.Append($"Sec-WebSocket-Protocol: {targetProtocol}\r\n");
                                                    }
                                                    sb.Append("\r\n");

                                                    var bytes = Encoding.ASCII.GetBytes(sb.ToString());
                                                    writer.Write(bytes);

                                                    string secWebSocketExtensions          = null;
                                                    var    keepAliveInterval               = 5000;
                                                    var    includeExceptionInCloseResponse = true;
                                                    var    webSocket = new WebSocket(_bufferFactory, stream, keepAliveInterval, secWebSocketExtensions, includeExceptionInCloseResponse, false, targetProtocol);
                                                    lock (_activeWebsockets)
                                                    {
                                                        _activeWebsockets.Add(webSocket);
                                                    }
                                                    handler(webSocket);
                                                    lock (_activeWebsockets)
                                                    {
                                                        _activeWebsockets.Remove(webSocket);
                                                    }
                                                }
                                                else
                                                {
                                                }

                                                return;
                                            }
                                            else
                                            {
                                                Log.WriteError("Not a valid websocket request");
                                            }
                                        }
                                        else
                                        {
                                            Log.WriteError("Failed parsing request method");
                                        }
                                    }
                                    else
                                    {
                                        Log.WriteError("Failed parsing request data");
                                    }

                                    requestCount++;
                                } while (keepAlive);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Write(e.ToString());
            }
            finally
            {
                client.Close();
            }
        }
Ejemplo n.º 34
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("6-7-9"))
                {
                    //科目树
                    FeesSubjectJson = Caches.GetFeesSubjectClassInfoToJson(-1, false, true);

                    bDate    = (HTTPRequest.GetString("bDate").Trim() != "") ? Convert.ToDateTime(HTTPRequest.GetString("bDate").Trim()) : DateTime.Now.AddDays(-(DateTime.Now.Day) + 1); //获得日期
                    eDate    = (HTTPRequest.GetString("eDate").Trim() != "") ? Convert.ToDateTime(HTTPRequest.GetString("eDate").Trim()) : DateTime.Now;                                  //获得日期
                    sType    = HTTPRequest.GetInt("seType", -1);                                                                                                                          //统计类型:0=明细统计,1=总账统计
                    getYear  = bDate.ToString("yyyy");
                    oneMonth = Convert.ToInt32(bDate.ToString("MM"));
                    status   = HTTPRequest.GetInt("get_status", 0);


                    //获得科目选择,遍历科目
                    fsubject = HTTPRequest.GetString("subject_hd");
                    result   = fsubject.Split(',');



                    if (ispost)
                    {
                        for (int i = 0; i < result.Length - 1; i++)
                        {
                            //获得科目所选节点科目名称
                            fsubjectName = CostDetails.getObjectsListName(Convert.ToInt32(result[i]));

                            //判断是否有子节点
                            tl = DataClass.ExistsFeesSubjectClassChild(Convert.ToInt32(result[i]));
                            if (tl)
                            {
                                dataclass = CostDetails.getTreeChildrenCount(result[i]); //找到子节点
                                string[] dclass = dataclass.Split(',');
                                for (int j = 0; j < dclass.Length - 1; j++)
                                {
                                    //获得月份
                                    mList         = CostDetails.getMonthBySubjectAndDateTime(Convert.ToInt32(dclass[j]), bDate, eDate);
                                    mdt           = mList.Copy();
                                    mdt.TableName = "m_" + j + c_count;
                                    mds.Tables.Add(mdt);


                                    //获得最大月
                                    maxList += CostDetails.getMonthBySubjectAndDateTime_Max(Convert.ToInt32(dclass[j]), bDate, eDate) + ",";
                                    //获得科目名称及编码
                                    objectName = CostDetails.getSubjectNameAndID(Convert.ToInt32(dclass[j]));

                                    //上年结转余额
                                    dList         = CostDetails.getOccurrenceAndBalanceDetails(bDate, eDate, Convert.ToInt32(dclass[j]), status);
                                    ydt           = dList.Copy();
                                    ydt.TableName = "y_" + j + c_count;
                                    yds.Tables.Add(ydt);

                                    c_count++;
                                }
                                //--====================================月份合成表=============================================
                                msCost = mds.Tables[0].Clone();                        //创建新表 克隆以有表的架构
                                object[] objmArray = new object[msCost.Columns.Count]; //定义与表列数相同的对象数组 存放表的一行的值
                                for (int m = 0; m < mds.Tables.Count; m++)
                                {
                                    if (mds.Tables[m].Rows.Count > 0)
                                    {
                                        for (int n = 0; n < mds.Tables[m].Rows.Count; n++)
                                        {
                                            mds.Tables[m].Rows[n].ItemArray.CopyTo(objmArray, 0); //将表的一行的值存放数组中
                                            msCost.Rows.Add(objmArray);                           //将数组的值添加到新表中
                                        }
                                    }
                                }
                                DataView dv = new DataView(msCost);
                                dv.Sort = "oMonth";
                                nTable  = dv.ToTable(true, "oMonth");
                                //=====================上年结存余额合成一张表==============================
                                ysCost = yds.Tables[0].Clone();                       //创建新表 克隆以有表的架构
                                object[] objArray = new object[ysCost.Columns.Count]; //定义与表列数相同的对象数组 存放表的一行的值
                                for (int m = 0; m < yds.Tables.Count; m++)
                                {
                                    if (yds.Tables[m].Rows.Count > 0)
                                    {
                                        for (int n = 0; n < yds.Tables[m].Rows.Count; n++)
                                        {
                                            yds.Tables[m].Rows[n].ItemArray.CopyTo(objArray, 0); //将表的一行的值存放数组中
                                            ysCost.Rows.Add(objArray);                           //将数组的值添加到新表中
                                        }
                                    }
                                }
                                if (ysCost.Rows.Count > 0)
                                {
                                    ycAccountMoney = Convert.ToDecimal(ysCost.Compute("sum(cAccountMoney)", "").ToString());
                                }

                                //====================找到科目中最大月========================================
                                string[] maxListArrary = maxList.Split(',');

                                for (int q = 0; q < maxListArrary.Length - 1; q++)
                                {
                                    if (maxListArrary[q].ToString() != "")
                                    {
                                        int mValue = Convert.ToInt32(maxListArrary[q].ToString());
                                        if (mValue > maxValue)
                                        {
                                            maxValue = mValue;
                                        }
                                    }
                                }
                                maxList = maxValue.ToString();
                            }
                            else
                            {
                                //上年结转余额
                                ysCost = CostDetails.getOccurrenceAndBalanceDetails(bDate, eDate, Convert.ToInt32(result[i]), status);
                                //获得月份
                                nTable = CostDetails.getMonthBySubjectAndDateTime(Convert.ToInt32(result[i]), bDate, eDate);
                                //获得最大月
                                maxList = CostDetails.getMonthBySubjectAndDateTime_Max(Convert.ToInt32(result[i]), bDate, eDate);
                                //获得科目名称及编码
                                objectName = CostDetails.getSubjectNameAndID(Convert.ToInt32(result[i]));
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("6-7-10"))
                {
                    bDate  = Utils.IsDateString(Utils.ChkSQL(HTTPRequest.GetString("bDate"))) ? DateTime.Parse(Utils.ChkSQL(HTTPRequest.GetString("bDate"))) : DateTime.Now.AddDays(-(DateTime.Now.Day) + 1);
                    eDate  = Utils.IsDateString(Utils.ChkSQL(HTTPRequest.GetString("eDate"))) ? DateTime.Parse(Utils.ChkSQL(HTTPRequest.GetString("eDate"))) : DateTime.Now;
                    sType  = HTTPRequest.GetInt("sType", 0);
                    status = HTTPRequest.GetInt("get_status", 0);//0=全部;1=已审核

                    if (ispost)
                    {
                        //按时间统计
                        if (sType == 0)
                        {
                            kList = CostDetails.getFeeSubjectID(bDate, eDate);
                            DataSet ds = new DataSet();
                            for (int i = 0; i < kList.Rows.Count; i++)
                            {
                                DataTable dt = CostDetails.getOccurrenceAndBalanceDetails(bDate, eDate, Convert.ToInt32(kList.Rows[i][0]), status);
                                dList           = dt.Copy();
                                dList.TableName = "t_" + i;
                                ds.Tables.Add(dList);
                            }
                            if (ds.Tables.Count > 0)
                            {
                                sCost = ds.Tables[0].Clone();                        //创建新表 克隆以有表的架构
                                object[] objArray = new object[sCost.Columns.Count]; //定义与表列数相同的对象数组 存放表的一行的值
                                for (int m = 0; m < ds.Tables.Count; m++)
                                {
                                    if (ds.Tables[m].Rows.Count > 0)
                                    {
                                        for (int n = 0; n < ds.Tables[m].Rows.Count; n++)
                                        {
                                            ds.Tables[m].Rows[n].ItemArray.CopyTo(objArray, 0); //将表的一行的值存放数组中
                                            sCost.Rows.Add(objArray);                           //将数组的值添加到新表中
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //按科目统计
                    if (sType == 1)
                    {
                        DataSet classDataSet = new DataSet();
                        getTreeNode = HTTPRequest.GetString("get_treeNode");
                        result      = getTreeNode.Split(',');


                        //把选择的科目整理到dataset中
                        for (int i = 0; i < result.Length - 1; i++)
                        {
                            DataTable tr = CostDetails.getObjectsListName(Convert.ToInt32(result[i]));

                            if (tr != null)
                            {
                                for (int p = 0; p < tr.Rows.Count; p++)
                                {
                                    TreeName += tr.Rows[p][0].ToString() + ",";
                                }
                            }
                            else
                            {
                                TreeName = "";
                            }

                            //获得科目名称
                            DataTable className = CostDetails.getClassName(result[i]);

                            DataTable ddt = className.Copy();
                            ddt.TableName = "k" + i + c_count;
                            classDataSet.Tables.Add(ddt);
                            c_count++;
                        }
                        if (classDataSet.Tables.Count > 0)
                        {
                            //把dataset中的datatable合并到一张表中
                            newTable = classDataSet.Tables[0].Clone();              //创建新表 克隆以有表的架构
                            object[] objArray = new object[newTable.Columns.Count]; //定义与表列数相同的对象数组 存放表的一行的值
                            for (int m = 0; m < classDataSet.Tables.Count; m++)
                            {
                                if (classDataSet.Tables[m].Rows.Count > 0)
                                {
                                    for (int n = 0; n < classDataSet.Tables[m].Rows.Count; n++)
                                    {
                                        classDataSet.Tables[m].Rows[n].ItemArray.CopyTo(objArray, 0); //将表的一行的值存放数组中
                                        newTable.Rows.Add(objArray);                                  //将数组的值添加到新表中
                                    }
                                }
                            }
                            if (TreeName.Length > 2)
                            {
                                TreeName = TreeName.Substring(0, TreeName.Length - 1);
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
Ejemplo n.º 36
0
        void tmrReport_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (reportProcess)
            {
                //    MessageHelper.Instance.WirteInfo("查询状态报告触发, 但上次处理仍在进行,退出,sends.count = " + sends.Count);
                return;
            }
            try
            {
                reportProcess = true;
                //   MessageHelper.Instance.WirteInfo("查询状态报告触发, sends.count = " + sends.Count);

                //            < returnsms >
                //< statusbox >
                //< mobile > 18666620923 </ mobile > -------------对应的手机号码
                //< taskid > 1212 </ taskid > -------------同一批任务ID
                //< status > 10 </ status > ---------状态报告----10:发送成功,20:发送失败
                //       < receivetime > 2011 - 12 - 02 22:12:11 </ receivetime > -------------接收时间
                //              < errorcode > DELIVRD </ errorcode > -上级网关返回值,不同网关返回值不同,仅作为参考
                //                     < extno > 01 </ extno > --子号,即自定义扩展号
                //                            </ statusbox >
                //                            < statusbox >
                //                            < mobile > 18666620923 </ mobile >
                //                            < taskid > 1212 </ taskid >
                //                            < status > 20 </ status >
                //                            < receivetime > 2011 - 12 - 02 22:12:11 </ receivetime >
                //                                   < errorcode > 2 </ errorcode >
                //                                   < extno ></ extno >
                //                                   </ statusbox >
                //                                   </ returnsms >


                if (sends.Count > 0)
                {
                    string   msgid    = "";
                    string   mobile   = "";
                    bool     ok       = true;
                    DateTime datetime = DateTime.Now;
                    string   post     = string.Format("action=report&userid={0}&account={1}&password={2}", userId, account, password);
                    //  MessageHelper.Instance.WirteInfo("请求状态报告内容:" + post);
                    //  MessageHelper.Instance.WirteInfo("请求状态报告地址:" + statusUrl);
                    string t = HTTPRequest.PostWebRequest(statusUrl, post, System.Text.Encoding.UTF8);
                    // MessageHelper.Instance.WirteInfo("原始状态报告:" + t);
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(t);
                    XmlElement root = null;
                    root = doc.DocumentElement;
                    XmlNodeList listNodes = root.ChildNodes;
                    foreach (XmlNode node in listNodes)
                    {
                        foreach (XmlNode cNode in node.ChildNodes)
                        {
                            switch (cNode.Name)
                            {
                            case "mid":
                                break;

                            case "mobile":
                                mobile = cNode.InnerText;
                                break;

                            case "status":
                                if (cNode.InnerText == "10")
                                {
                                    ok = true;
                                }
                                else
                                {
                                    ok = false;
                                }
                                break;

                            case "taskid":
                                msgid = cNode.InnerText;
                                break;

                            case "receivetime":

                                if (!DateTime.TryParse(cNode.InnerText, out datetime))
                                {
                                    datetime = DateTime.Now;
                                }
                                break;
                            }
                        }
                        if (ReportEvent != null)
                        {
                            ushort statecode;
                            string statetext = "发送成功。";
                            statecode = 2100;
                            if (!ok)
                            {
                                statecode = 2101;
                                statetext = "发送失败。";
                            }
                            lock (sendslocker)
                            {
                                var se = sends.FirstOrDefault(s => s.Value.SendEventArgs.SerialNumber.StartsWith(msgid) && s.Value.SendEventArgs.Numbers[0] == mobile);
                                if (!se.Equals(default(KeyValuePair <string, ExSendEventArgs>)))
                                {
                                    ReportEventArgs re = new ReportEventArgs(se.Value.SendEventArgs.SerialNumber, ok, statecode, statetext, datetime);
                                    ReportEvent(this, re);
                                    string tr = JsonSerialize.Instance.Serialize <ReportEventArgs>(re);
                                    MessageHelper.Instance.WirteInfo("返回状态报告:" + tr);
                                    //  LogClient.LogHelper.LogInfo("OPWO", "GetReport Process ->", tr);
                                    sends.Remove(re.SerialNumber);
                                }
                            }
                        }
                    }
                }

                lock (sendslocker)
                {
                    List <string> rkeys = new List <string>();
                    foreach (string key in sends.Keys)
                    {
                        if ((DateTime.Now - sends[key].Time).TotalDays >= 2)
                        {
                            ReportEventArgs re = new ReportEventArgs(sends[key].SendEventArgs.SerialNumber, true, 2100, "状态报告超时,默认成功.", DateTime.Now);
                            ReportEvent(this, re);
                            string ttr = JsonSerialize.Instance.Serialize <ReportEventArgs>(re);
                            MessageHelper.Instance.WirteInfo("超时返回状态报告:" + JsonSerialize.Instance.Serialize <ReportEventArgs>(re));
                            LogClient.LogHelper.LogInfo("OPWO", "GetReport Timeout ->", ttr);
                            rkeys.Add(key);
                        }
                    }
                    foreach (string key in rkeys)
                    {
                        sends.Remove(key);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageHelper.Instance.WirteError("OPWO,GetReport Error", ex);
                LogClient.LogHelper.LogInfo("OPWO", "GetReport Error ->", ex.Message);
            }
            reportProcess = false;
        }
Ejemplo n.º 37
0
        private void ReadHttpStream(HTTPRequest request, HTTPResponse response)
        {
            string localfile = this.m_DownloadInfo.tempPath;

            try
            {
                List <byte[]> streamedFragments = response.GetStreamedFragments();
                if (streamedFragments != null)
                {
                    int num = 0;
                    using (FileStream fileStream = new FileStream(localfile, FileMode.Append))
                    {
                        foreach (byte[] array in streamedFragments)
                        {
                            num += array.Length;
                            fileStream.Write(array, 0, array.Length);
                        }
                    }
                    this.m_DownloadInfo.downloadedSize += num;
                }
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("An error occured while downloading {0} due to {1}.Cancelling!", localfile, ex);
                this.m_DownloadInfo.result = DownloadResult.Failed;
                //EventManager.Instance.Trigger<SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "failure", this.m_DownloadInfo.downloadedSize).Trigger();
                CancelDownload(true);
                this.CancelDownload(true);
                return;
            }

            float num2 = (float)this.m_DownloadInfo.downloadedSize / (float)this.m_DownloadInfo.downloadSize;

            this.m_DownloadInfo.currProgress = num2;

            Debug.LogFormat("Downloading {0} Status: Range {1}/{2} ({3:0.00})", this.m_DownloadInfo.fileName, this.m_DownloadInfo.downloadedSize, this.m_DownloadInfo.downloadSize, this.m_DownloadInfo.currProgress);
            if (!response.IsStreamingFinished || request.State != HTTPRequestStates.Finished)
            {
                return;
            }

            Debug.LogFormat("Download finished : {0}", this.m_DownloadInfo.savePath);
            this.m_DownloadInfo.currProgress = 1.0f;

            // 续传完成后,做一手MD5验证
            string localMd5 = AssetUtils.BuildFileMd5(localfile);

            if (localMd5.Trim() != m_DownloadInfo.fileMd5.Trim())
            {
                //md5验证失败,删除临时文件
                if (File.Exists(localfile))
                {
                    File.Delete(localfile);
                }

                Debug.LogError("md5 error, retry download:" + localfile + " =>" + localMd5 + " ## " + m_DownloadInfo.fileMd5);
                this.m_DownloadInfo.result       = DownloadResult.Md5Error;
                this.m_DownloadInfo.currProgress = 0.0f;
                CancelDownload(true);
            }
            else
            {// md5验证通过,临时文件转为最终文件
                string localfile2 = m_DownloadInfo.savePath;
                if (File.Exists(localfile2))
                {
                    File.Delete(localfile2);
                }

                File.Move(localfile, localfile2);
                this.m_DownloadInfo.result = DownloadResult.Success;
                DownloadManager.Inst.FinishDownloadTask(this.m_DownloadInfo);
            }

            //EventManager.Instance.Trigger<SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "finish", m_DownloadInfo.downloadedSize).Trigger();
        }
 // Send the request
 private void SendDownloadRequest(HTTPRequest request)
 {
     Debug.Log("Sending HTTP Request to " + request.Uri.AbsoluteUri);
     request.Send();
 }
Ejemplo n.º 39
0
 public object Perform(HTTPRequest hr, ref string targetFile)
 {
     return(hr.Json);
 }
 private void DoHeadRequest(HTTPRequest request)
 {
     Debug.Log("Sending HEAD request to " + request.Uri.AbsoluteUri);
     request.Send();
 }
 private void OnHeadRequestError(HTTPRequest request)
 {
     Debug.LogError("Error making HEAD request: " + request.Exception.Message);
     BeginHeadRequest(m_RemoteFileMetadata.GetFileFragmentDataFromUri(request.Uri.AbsoluteUri));
 }
Ejemplo n.º 42
0
        public string get(HTTPRequest r)
        {
            string body   = "Request method=" + r.method;
            int    status = 400;
            Dictionary <string, string> arguments = new Dictionary <string, string>();

            string[] path_query = r.url.Split('?');
            string   path       = path_query[0];


            try
            {
                if (r.method != "GET")
                {
                    throw new SamanaException(405, "Method not Allowed");
                }
                if (path_query.Length > 2)
                {
                    throw new SamanaException(500, "Bad Query");
                }

                if (path_query.Length > 1)
                {
                    string[] args = path_query[1].Split('&');
                    for (int i = 0; i < args.Length; i++)
                    {
                        string[] t = args[i].Split('=');
                        if (t.Length == 1)
                        {
                            arguments.Add(t[0], "1");
                        }
                        else if (t.Length == 2)
                        {
                            arguments.Add(t[0], t[1]);
                        }
                        else
                        {
                            throw new SamanaException(500, "Bad Query");
                        }
                    }
                }
                if (path == "/cpu")
                {
                    body   = cpudata.json();
                    status = 200;
                }
                else if (path == "/ram")
                {
                    body   = ramdata.json();
                    status = 200;
                }
                else if (path == "/uptime")
                {
                    body   = uptime.ToString();
                    status = 200;
                }
                else if (path == "/syslog")
                {
                    body   = syslog.json();
                    status = 200;
                }
                else if (path == "/applog")
                {
                    body   = applog.json();
                    status = 200;
                }
                else if (path == "/services")
                {
                    body   = Services.json();
                    status = 200;
                }
                else if (path == "/hddrives")
                {
                    body   = hdlist.json();
                    status = 200;
                }
                else if (path == "/processes")
                {
                    body   = allProcesses.json();
                    status = 200;
                }
                else if (path == "/log")
                {
                    try
                    {
                        int    e = -1;
                        int    h = 2;
                        int    l = 3;
                        string logname;

                        if (!arguments.ContainsKey("logname"))
                        {
                            throw new Exception("Missing log name");
                        }

                        logname = System.Uri.UnescapeDataString(arguments["logname"]);
                        if (arguments.ContainsKey("eventId"))
                        {
                            if (!int.TryParse(arguments["eventId"], out e))
                            {
                                e = -1;
                            }
                        }

                        if (arguments.ContainsKey("hours"))
                        {
                            if (!int.TryParse(arguments["hours"], out h))
                            {
                                h = 2;
                            }
                        }

                        if (arguments.ContainsKey("level"))
                        {
                            if (!int.TryParse(arguments["level"], out l))
                            {
                                l = 3;
                            }
                        }

                        EventList evtlist = new EventList(logname, l, h, 1, config.debug_level);
                        evtlist.Poll(1);

                        body   = evtlist.json();
                        status = 200;
                    }
                    catch (Exception e)
                    {
                        evtlog.error(e.Message + e.StackTrace, 2);
                        throw new SamanaException(500, "Bad Query");
                    }
                }
                else if (path == "/sessions")
                {
                    sessions.Poll();
                    body   = sessions.json();
                    status = 200;
                }
                else if (path == "/version")
                {
                    body   = "\"" + this.version + "\"";
                    status = 200;
                }
                else
                {
                    throw new SamanaException(404, "Not Found");
                }
            }
            catch (SamanaException e)
            {
                status = e.status;
                body   = e.body;
            }

            HTTPResponse res = new HTTPResponse(status, body);

            return(res.ToString());
        }
Ejemplo n.º 43
0
        private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // Clear the PollRequest variable, so we can start a new poll.
            PollRequest = null;

            if (State == TransportStates.Closed)
            {
                return;
            }

            string errorString = null;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:

                if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("PollingTransport", "OnPollRequestFinished: " + resp.DataAsText);
                }

                if (resp.IsSuccess)
                {
                    ParseResponse(resp);
                }
                else
                {
                    errorString = string.Format("Polling - Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
                                                resp.StatusCode,
                                                resp.Message,
                                                resp.DataAsText,
                                                req.CurrentUri);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                errorString = req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception";
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                errorString = string.Format("Polling - Request({0}) Aborted!", req.CurrentUri);
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                errorString = string.Format("Polling - Connection Timed Out! Uri: {0}", req.CurrentUri);
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                errorString = string.Format("Polling - Processing the request({0}) Timed Out!", req.CurrentUri);
                break;
            }

            if (!string.IsNullOrEmpty(errorString))
            {
                (Manager as IManager).OnTransportError(this, errorString);
            }
        }
Ejemplo n.º 44
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string data = "";
            string Act  = HTTPRequest.GetString("Act");

            if (Act.Trim() != "")
            {
                //对账单
                if (Act == "d")
                {
                    int msid = HTTPRequest.GetInt("msid", 0);
                    if (msid > 0)
                    {
                        MonthlyStatementInfo msi = MonthlyStatements.GetMonthlyStatementInfoModel(msid);
                        if (msi != null)
                        {
                            data = "" + config.Sysurl + "/m-" + msi.MonthlyStatementID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(msi.LastPrintDateTime.ToString() + "|" + msi.sCode, config.Passwordkey)).Trim();
                        }
                    }
                }
            }
            else
            {
                OrderInfo oi = new OrderInfo();
                orderid   = HTTPRequest.GetInt("orderid", 0);
                ordertype = HTTPRequest.GetInt("ordertype", 0);
                if (orderid > 0)
                {
                    oi = Orders.GetOrderInfoModel(orderid);
                    if (oi != null)
                    {
                        data = "" + config.Sysurl + "/o-" + oi.OrderID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(oi.LastPrintDateTime.ToString() + "|" + oi.oOrderNum, config.Passwordkey)).Trim();
                    }
                }
            }
            if (data != "")
            {
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;

                int scale = 2;
                qrCodeEncoder.QRCodeScale = scale;

                int version = 5;
                qrCodeEncoder.QRCodeVersion = version;

                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;

                System.Drawing.Image image;

                //String data = "MEBKM:TITLE:OrderID(" + oi.oOrderNum + "),PrintTime(" + oi.LastPrintDateTime + ");URL:" + config.Sysurl + "/o-" + oi.OrderID + ".aspx?rc=" + Utils.UrlEncode(DES.Encode(oi.LastPrintDateTime.ToString() + "|" + oi.oOrderNum, config.Passwordkey)).Trim() + ";;";

                //String data = oi.oOrderNum;
                image = qrCodeEncoder.Encode(data);
                try
                {
                    byte[] bBuffer = PhotoImageInsert(image);
                    Response.ClearContent();
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(bBuffer);
                }
                finally
                {
                    image.Dispose();
                    Response.End();
                }
            }
        }
Ejemplo n.º 45
0
        public bool Connect()
        {
            try
            {
                string post = string.Format("action=overage&userid={0}&account={1}&password={2}", userId, account, password);
                string t    = HTTPRequest.PostWebRequest(balanceUrl, post, Encoding.UTF8);
                // MessageHelper.Instance.WirteInfo("连接原始返回消息:" + t);
                //             <? xml version = "1.0" encoding = "utf-8" ?>
                //< returnsms >
                //< returnstatus > status </ returnstatus > --------------返回状态值:成功返回Success 失败返回:Faild
                //       <message> message</ message > --------------返回信息提示:见下表
                //           <payinfo> payinfo</ payinfo > --------------返回支付方式  后付费,预付费
                //               <overage> overage</ overage > -------------返回已发送条数
                //                < sendTotal > sendTotal </ sendTotal > -------返回总点数  当支付方式为预付费是返回总充值点数
                //                       </ returnsms >

                bool        ok = false;
                string      overage = "", msg = "";
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(t);
                XmlElement root = null;
                root = doc.DocumentElement;
                XmlNodeList listNodes = root.ChildNodes;
                foreach (XmlNode node in listNodes)
                {
                    switch (node.Name)
                    {
                    case "returnstatus":
                        ok = (node.InnerText == "Sucess") ? true : false;
                        break;

                    case "overage":
                        overage = node.InnerText;
                        break;

                    case "message":
                        msg = node.InnerText;
                        break;
                    }
                }
                Console.WriteLine("连接消息 : " + msg);
                Console.WriteLine("余额 : " + overage);
                if (ok)
                {
                    tmrMO.Start();
                    tmrReport.Start();
                    MessageHelper.Instance.WirteInfo("状态报告和上行短信查询服务启动!");
                    return(true);
                }
                else
                {
                    MessageHelper.Instance.WirteInfo("连接失败");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                LogClient.LogHelper.LogInfo("OPWO", "Connect Error ->", ex.Message);
            }
            return(false);
        }
Ejemplo n.º 46
0
        IEnumerator DownloadAssetBundle()
        {
            downloading = true;

            // Create and send our request
            var request = new HTTPRequest(new Uri(URL)).Send();

            status = "Download started";

            // Wait while it's finishes and add some fancy dots to display something while the user waits for it.
            // A simple "yield return StartCoroutine(request);" would do the job too.
            while (request.State < HTTPRequestStates.Finished)
            {
                yield return(new WaitForSeconds(0.1f));

                status += ".";
            }

            // Check the outcome of our request.
            switch (request.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:

                if (request.Response.IsSuccess)
                {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                    status = string.Format("AssetBundle downloaded! Loaded from local cache: {0}", request.Response.IsFromCache.ToString());
#else
                    status = "AssetBundle downloaded!";
#endif

                    // Start creating the downloaded asset bundle
                    AssetBundleCreateRequest async =
#if UNITY_5_3
                        AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#else
                        AssetBundle.CreateFromMemory(request.Response.Data);
#endif

                    // wait for it
                    yield return(async);

                    // And process the bundle
                    yield return(StartCoroutine(ProcessAssetBundle(async.assetBundle)));
                }
                else
                {
                    status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           request.Response.StatusCode,
                                           request.Response.Message,
                                           request.Response.DataAsText);
                    Debug.LogWarning(status);
                }

                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                status = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
                Debug.LogError(status);
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                status = "Request Aborted!";
                Debug.LogWarning(status);
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                status = "Connection Timed Out!";
                Debug.LogError(status);
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                status = "Processing the request Timed Out!";
                Debug.LogError(status);
                break;
            }

            downloading = false;
        }
Ejemplo n.º 47
0
        void tmrMO_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                string   msgid    = "";
                string   msg      = "";
                string   mobile   = "";
                string   extno    = "";
                DateTime datetime = DateTime.Now;
                string   post     = string.Format("action=mo&userid={0}&account={1}&password={2}", userId, account, password);
                string   t        = HTTPRequest.PostWebRequest(moUrl, post, System.Text.Encoding.UTF8);
                //MessageHelper.Instance.WirteInfo(t);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(t);
                XmlElement root = null;
                root = doc.DocumentElement;
                XmlNodeList listNodes = root.ChildNodes;
                foreach (XmlNode node in listNodes)
                {
                    foreach (XmlNode cNode in node.ChildNodes)
                    {
                        switch (cNode.Name)
                        {
                        case "mobile":
                            mobile = cNode.InnerText;
                            break;

                        case "content":
                            msg = cNode.InnerText;
                            break;

                        case "taskid":
                            msgid = cNode.InnerText;
                            break;

                        case "extno":
                            extno = cNode.InnerText;
                            break;

                        case "receivetime":

                            if (!DateTime.TryParse(cNode.InnerText, out datetime))
                            {
                                datetime = DateTime.Now;
                            }
                            break;
                        }
                    }
                    if (DeliverEvent != null)
                    {
                        DeliverEventArgs re = new DeliverEventArgs(Guid.NewGuid().ToString(), datetime, msg, mobile, extno, "");
                        DeliverEvent(this, re);
                        string tr = JsonSerialize.Instance.Serialize <DeliverEventArgs>(re);
                        LogClient.LogHelper.LogInfo("OPWO", "MO ->", tr);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageHelper.Instance.WirteError(ex.ToString());
                LogClient.LogHelper.LogInfo("OPWO", "MO Error ->", ex.Message);
            }
        }
Ejemplo n.º 48
0
 private Dictionary <string, object> GetSessionContext(HTTPRequest request) => request.session.Data.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Ejemplo n.º 49
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("7-2-1-7-1"))
                {
                    sDate         = Utils.IsDateString(Utils.ChkSQL(HTTPRequest.GetString("sDate"))) ? DateTime.Parse(Utils.ChkSQL(HTTPRequest.GetString("sDate"))) : DateTime.Now.AddDays(-(DateTime.Now.Day) + 1);
                    stDate        = Utils.IsDateString(Utils.ChkSQL(HTTPRequest.GetString("stDate"))) ? DateTime.Parse(Utils.ChkSQL(HTTPRequest.GetString("stDate"))) : DateTime.Now;
                    Act           = HTTPRequest.GetString("Act");
                    selectClasses = HTTPRequest.GetInt("getCategory", 0);
                    if (ispost)
                    {
                        //客户明细
                        if (selectClasses == 0)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                        }
                        //品牌明细
                        if (selectClasses == 1)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                        }
                        //单品明细
                        if (selectClasses == 2)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                        }
                        //区域明细
                        if (selectClasses == 3)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                        }
                        //业务员明细
                        if (selectClasses == 4)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                        }
                    }
                    else
                    {
                        if (Act.IndexOf("act") > -1)
                        {
                            spList = buySaleDetailsOfClasses.getBuySaleDetalsOfStorehouse(sDate, stDate, selectClasses);
                            DataTable dt = new DataTable();
                            DataSet   ds = new DataSet();
                            dt = spList.Copy();
                            ds.Tables.Add(dt);

                            if (selectClasses == 0)
                            {
                                ds.Tables[0].Columns[0].ColumnName = "客户名称";
                                ds.Tables[0].Columns[1].ColumnName = "类别";
                                ds.Tables[0].Columns[2].ColumnName = "数量";
                                ds.Tables[0].Columns[3].ColumnName = "金额";
                            }
                            if (selectClasses == 1)
                            {
                                ds.Tables[0].Columns[0].ColumnName = "品牌名称";
                                ds.Tables[0].Columns[1].ColumnName = "数量";
                                ds.Tables[0].Columns[2].ColumnName = "金额";
                            }
                            if (selectClasses == 2)
                            {
                                ds.Tables[0].Columns[0].ColumnName = "商品名称";
                                ds.Tables[0].Columns[1].ColumnName = "商品条码";
                                ds.Tables[0].Columns[2].ColumnName = "数量";
                                ds.Tables[0].Columns[3].ColumnName = "金额";
                            }
                            if (selectClasses == 3)
                            {
                                ds.Tables[0].Columns[0].ColumnName = "区域名称";
                                ds.Tables[0].Columns[1].ColumnName = "数量";
                                ds.Tables[0].Columns[2].ColumnName = "金额";
                            }
                            if (selectClasses == 4)
                            {
                                ds.Tables[0].Columns[0].ColumnName = "业务员名称";
                                ds.Tables[0].Columns[1].ColumnName = "数量";
                                ds.Tables[0].Columns[2].ColumnName = "金额";
                            }
                            CreateExcel(ds.Tables[0], "购销明细数据_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls");
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
Ejemplo n.º 50
0
        void getOrder()
        {
            string uri = "https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete";

            HTTPRequest.init().sendPOST(uri, new Dictionary <string, string> {
                { "_json_att", "" }
            }, (JsonObject json) =>
            {
                Debug.WriteLine("得到未完成订单" + json.ToString());
                if (!json.ContainsKey("data"))
                {
                    noOrder();
                    return;
                }
                JsonObject data = json["data"].GetObject();

                if (data.Count >= 2)
                {
                    jixuOrder();
                    JsonArray orderDBList = data["orderDBList"].GetArray();

                    if (orderDBList.Count > 0)
                    {
                        JsonObject jsonOrder = orderDBList[0].GetObject();

                        labChengCheRiQi.Text = jsonOrder["start_train_date_page"].ToString();
                        labCheCi.Text        = jsonOrder["train_code_page"].ToString();

                        JsonArray from_station_name_page = jsonOrder["from_station_name_page"].GetArray();
                        JsonArray to_station_name_page   = jsonOrder["to_station_name_page"].GetArray();
                        labChuFaDi.Text      = from_station_name_page[0].ToString() + jsonOrder["start_time_page"].ToString() + "开";
                        labMuDiDI.Text       = to_station_name_page[0].GetString() + jsonOrder["arrive_time_page"].ToString() + "到";
                        labZongZhangShu.Text = jsonOrder["ticket_totalnum"].GetNumber() + "张";
                        labZongPiaoKuan.Text = jsonOrder["ticket_price_all"].GetNumber() / 100 + "元";
                        sequence_no          = jsonOrder["sequence_no"].GetString();


                        JsonArray tickets = jsonOrder["tickets"].GetArray();
                        for (int i = 0; i < tickets.Count; i++)
                        {
                            JsonObject ticke          = tickets[i].GetObject();
                            JsonObject passengerDTO   = ticke["passengerDTO"].GetObject();
                            JYUserOrderInfo orderinfo = new JYUserOrderInfo();

                            orderinfo.labName.Text             = passengerDTO["passenger_name"].ToString();
                            orderinfo.labZhengJianLeiXing.Text = passengerDTO["passenger_id_type_name"].ToString();
                            orderinfo.labZhengJianHao.Text     = passengerDTO["passenger_id_no"].ToString();
                            orderinfo.labPiaoZhong.Text        = ticke["ticket_type_name"].ToString();
                            orderinfo.labXiBie.Text            = ticke["seat_type_name"].ToString();
                            orderinfo.labCheXiang.Text         = ticke["coach_no"].ToString();
                            orderinfo.labXiWeiHao.Text         = ticke["seat_name"].ToString();
                            orderinfo.labPiaoJia.Text          = ticke["str_ticket_price_page"].ToString();
                            stack.Children.Add(orderinfo);
                        }
                    }
                    else
                    {
                        noOrder();
                    }
                }
                else
                {
                    noOrder();
                }
            }, (string err) => {
                Debug.WriteLine("得到未完成订单" + err.ToString());
            });
        }
Ejemplo n.º 51
0
        public static void HandleResponse(string context, HTTPRequest request, out bool resendRequest, out HTTPConnectionStates proposedConnectionState, ref KeepAliveHeader keepAlive, LoggingContext loggingContext1 = null, LoggingContext loggingContext2 = null, LoggingContext loggingContext3 = null)
        {
            resendRequest           = false;
            proposedConnectionState = HTTPConnectionStates.Processing;

            if (request.Response != null)
            {
#if !BESTHTTP_DISABLE_COOKIES
                // Try to store cookies before we do anything else, as we may remove the response deleting the cookies as well.
                if (request.IsCookiesEnabled)
                {
                    CookieJar.Set(request.Response);
                }
#endif

                switch (request.Response.StatusCode)
                {
                // Not authorized
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
                case 401:
                {
                    string authHeader = DigestStore.FindBest(request.Response.GetHeaderValues("www-authenticate"));
                    if (!string.IsNullOrEmpty(authHeader))
                    {
                        var digest = DigestStore.GetOrCreate(request.CurrentUri);
                        digest.ParseChallange(authHeader);

                        if (request.Credentials != null && digest.IsUriProtected(request.CurrentUri) && (!request.HasHeader("Authorization") || digest.Stale))
                        {
                            resendRequest = true;
                        }
                    }

                    goto default;
                }

                // Redirected
                case 301:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2
                case 302:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3
                case 307:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8
                case 308:     // http://tools.ietf.org/html/rfc7238
                {
                    if (request.RedirectCount >= request.MaxRedirects)
                    {
                        goto default;
                    }
                    request.RedirectCount++;

                    string location = request.Response.GetFirstHeaderValue("location");
                    if (!string.IsNullOrEmpty(location))
                    {
                        Uri redirectUri = ConnectionHelper.GetRedirectUri(request, location);

                        if (HTTPManager.Logger.Level == Logger.Loglevels.All)
                        {
                            HTTPManager.Logger.Verbose("HTTPConnection", string.Format("[{0}] - Redirected to Location: '{1}' redirectUri: '{1}'", context, location, redirectUri), loggingContext1, loggingContext2, loggingContext3);
                        }

                        if (redirectUri == request.CurrentUri)
                        {
                            HTTPManager.Logger.Information("HTTPConnection", string.Format("[{0}] - Redirected to the same location!", context), loggingContext1, loggingContext2, loggingContext3);
                            goto default;
                        }

                        // Let the user to take some control over the redirection
                        if (!request.CallOnBeforeRedirection(redirectUri))
                        {
                            HTTPManager.Logger.Information("HTTPConnection", string.Format("[{0}] OnBeforeRedirection returned False", context), loggingContext1, loggingContext2, loggingContext3);
                            goto default;
                        }

                        // Remove the previously set Host header.
                        request.RemoveHeader("Host");

                        // Set the Referer header to the last Uri.
                        request.SetHeader("Referer", request.CurrentUri.ToString());

                        // Set the new Uri, the CurrentUri will return this while the IsRedirected property is true
                        request.RedirectUri = redirectUri;

                        request.IsRedirected = true;

                        resendRequest = true;
                    }
                    else
                    {
                        throw new Exception(string.Format("[{0}] Got redirect status({1}) without 'location' header!", context, request.Response.StatusCode.ToString()));
                    }

                    goto default;
                }

#if !BESTHTTP_DISABLE_CACHING
                case 304:
                    if (request.DisableCache)
                    {
                        break;
                    }

                    if (ConnectionHelper.LoadFromCache(context, request, loggingContext1, loggingContext2, loggingContext3))
                    {
                        request.Timing.Add(TimingEventNames.Loading_From_Cache);
                        HTTPManager.Logger.Verbose("HTTPConnection", string.Format("[{0}] - HandleResponse - Loaded from cache successfully!", context), loggingContext1, loggingContext2, loggingContext3);

                        // Update any caching value
                        HTTPCacheService.SetUpCachingValues(request.CurrentUri, request.Response);
                    }
                    else
                    {
                        HTTPManager.Logger.Verbose("HTTPConnection", string.Format("[{0}] - HandleResponse - Loaded from cache failed!", context), loggingContext1, loggingContext2, loggingContext3);
                        resendRequest = true;
                    }

                    break;
#endif

                default:
#if !BESTHTTP_DISABLE_CACHING
                    ConnectionHelper.TryStoreInCache(request);
#endif
                    break;
                }

                // Closing the stream is done manually?
                if (request.Response != null && !request.Response.IsClosedManually)
                {
                    // If we have a response and the server telling us that it closed the connection after the message sent to us, then
                    //  we will close the connection too.
                    bool closeByServer = request.Response.HasHeaderWithValue("connection", "close");
                    bool closeByClient = !request.IsKeepAlive;

                    if (closeByServer || closeByClient)
                    {
                        proposedConnectionState = HTTPConnectionStates.Closed;
                    }
                    else if (request.Response != null)
                    {
                        var keepAliveheaderValues = request.Response.GetHeaderValues("keep-alive");
                        if (keepAliveheaderValues != null && keepAliveheaderValues.Count > 0)
                        {
                            if (keepAlive == null)
                            {
                                keepAlive = new KeepAliveHeader();
                            }
                            keepAlive.Parse(keepAliveheaderValues);
                        }
                    }
                }

                // Null out the response here instead of the redirected cases (301, 302, 307, 308)
                //  because response might have a Connection: Close header that we would miss to process.
                // If Connection: Close is present, the server is closing the connection and we would
                // reuse that closed connection.
                if (resendRequest)
                {
                    // Discard the redirect response, we don't need it any more
                    request.Response = null;

                    if (proposedConnectionState == HTTPConnectionStates.Closed)
                    {
                        proposedConnectionState = HTTPConnectionStates.ClosedResendRequest;
                    }
                }
            }
        }
Ejemplo n.º 52
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("7-1-2"))
                {
                    si         = tbStoresInfo.GetStoresInfoModel(StoresID);
                    sName      = HTTPRequest.GetString("SName");
                    List       = storehouseStorage.RegionName();
                    Act        = HTTPRequest.GetString("act");//获取客户端post过来Act的值
                    bType      = HTTPRequest.GetInt("id", -1);
                    sList      = storehouseStorage.getStaffName();
                    sfname     = HTTPRequest.GetString("");
                    yList      = storehouseStorage.getSalesYear();
                    Export_Act = HTTPRequest.GetString("Act");

                    //获取前台传过来的区域得到区域ID
                    get_rName = HTTPRequest.GetString("rName");
                    rID       = storehouseStorage.GetRegionIDByName(get_rName);
                    //根据传过来的门店名称找到该门店的编号:表tbStoresInfo
                    get_storageName = HTTPRequest.GetString("storageName");
                    StoresID        = storehouseStorage.getStorageIDByName(get_storageName);
                    //根据营业员名称得到营业员id
                    get_staffName = HTTPRequest.GetString("staffName");
                    staffID       = storehouseStorage.getStaffIDByName(get_staffName);
                    //获取客户端过来的选择类型
                    get_reTypeValue = HTTPRequest.GetString("reTypeValue");
                    reType          = HTTPRequest.GetInt("reTypeValue", -1);
                    //获取客户端过来的联营类型
                    associated  = HTTPRequest.GetString("associated");
                    _associated = HTTPRequest.GetInt("_associated", -1);

                    //获取选择的日期
                    sDate  = (HTTPRequest.GetString("sDate").Trim() != "") ? Convert.ToDateTime(HTTPRequest.GetString("sDate").Trim() + " 00:00:00") : DateTime.Now.AddDays(-(DateTime.Now.Day) + 1);
                    stDate = (HTTPRequest.GetString("stDate").Trim() != "") ? Convert.ToDateTime(HTTPRequest.GetString("stDate").Trim() + " 23:59:59") : DateTime.Now;

                    if (ispost)
                    {
                        if (bType == 0)
                        {
                            if (Act == "act")
                            {
                                name   = HTTPRequest.GetString("path");    //获取客户端post过来的区域值
                                sfName = HTTPRequest.GetString("pathend"); //获取客户端post过来的门店值
                                rName  = HTTPRequest.GetString("pathRname");

                                if (name.Trim() != "")
                                {
                                    list = storehouseStorage.StaffNameByRegionName(name);

                                    for (int i = 0; i < list.Rows.Count; i++)
                                    {
                                        Response.Write(list.Rows[i][0].ToString() + ",");
                                    }
                                    Response.End();
                                }
                                if (sfName.Trim() != "")
                                {
                                    List = storehouseStorage.GetStorageName(rName, sfName);
                                    for (int i = 0; i < List.Rows.Count; i++)
                                    {
                                        Response.Write(List.Rows[i][0].ToString() + ",");
                                    }
                                    Response.End();
                                }
                            }
                            else
                            {
                                if (sDate > stDate)
                                {
                                    AddErrLine("日期区间选择错误,请重新选择!");
                                }
                                else
                                {
                                    dList = storehouseStorage.GetStorehouseStorageReport(rID, StoresID, staffID, sDate, stDate, reType, _associated);
                                }
                            }
                        }
                        if (bType == 1)
                        {
                            s_year = HTTPRequest.GetString("s_year");
                        }
                    }
                    else
                    {
                        if (Export_Act.IndexOf("act") > -1)
                        {
                            if (bType == 0)
                            {
                                DataTable dt = new DataTable();
                                DataSet   ds = new DataSet();
                                dList = storehouseStorage.GetStorehouseStorageReport(rID, StoresID, staffID, sDate, stDate, reType, _associated);
                                dt    = dList.Copy();
                                dt.Columns.RemoveAt(0);
                                ds.Tables.Add(dt);
                                ds.Tables[0].Columns[0].ColumnName  = "商品条码";
                                ds.Tables[0].Columns[1].ColumnName  = "商品名称";
                                ds.Tables[0].Columns[2].ColumnName  = "装件数";
                                ds.Tables[0].Columns[3].ColumnName  = "期初数";
                                ds.Tables[0].Columns[4].ColumnName  = "进货数量";
                                ds.Tables[0].Columns[5].ColumnName  = "销售数量";
                                ds.Tables[0].Columns[6].ColumnName  = "进货金额";
                                ds.Tables[0].Columns[7].ColumnName  = "销售金额";
                                ds.Tables[0].Columns[8].ColumnName  = "期初金额";
                                ds.Tables[0].Columns[9].ColumnName  = "赠品数量";
                                ds.Tables[0].Columns[10].ColumnName = "赠品金额";
                                ds.Tables[0].Columns[11].ColumnName = "样品数量";
                                ds.Tables[0].Columns[12].ColumnName = "样品金额";
                                ds.Tables[0].Columns[13].ColumnName = "退货数量";
                                ds.Tables[0].Columns[14].ColumnName = "退货金额";

                                CreateExcel(ds.Tables[0], "客户进销存报表_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls");
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
Ejemplo n.º 53
0
        protected virtual void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    DateTime downloadStarted = (DateTime)req.Tag;
                    TimeSpan diff            = DateTime.Now - downloadStarted;

                    this._statusText.text = string.Format("Streaming finished in {0:N0}ms", diff.TotalMilliseconds);
                }
                else
                {
                    this._statusText.text = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                          resp.StatusCode,
                                                          resp.Message,
                                                          resp.DataAsText);
                    Debug.LogWarning(this._statusText.text);

                    request = null;
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                this._statusText.text = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                Debug.LogError(this._statusText.text);

                request = null;
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                this._statusText.text = "Request Aborted!";
                Debug.LogWarning(this._statusText.text);

                request = null;
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                this._statusText.text = "Connection Timed Out!";
                Debug.LogError(this._statusText.text);

                request = null;
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                this._statusText.text = "Processing the request Timed Out!";
                Debug.LogError(this._statusText.text);

                request = null;
                break;
            }

            // UI

            this._streamingSetupRoot.gameObject.SetActive(true);
            this._reportingRoot.gameObject.SetActive(false);

            this._startDownload.interactable  = true;
            this._cancelDownload.interactable = false;
            request = null;
        }
Ejemplo n.º 54
0
        private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            if (this.State == ConnectionStates.CloseInitiated)
            {
                SetState(ConnectionStates.Closed);
                return;
            }

            string errorReason = null;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("HubConnection", "Negotiation Request Finished Successfully! Response: " + resp.DataAsText);

                    // Parse negotiation
                    this.NegotiationResult = NegotiationResult.Parse(resp.DataAsText, out errorReason, this);

                    // TODO: check validity of the negotiation result:
                    //  If url and accessToken is present, the other two must be null.
                    //  https://github.com/aspnet/SignalR/blob/dev/specs/TransportProtocols.md#post-endpoint-basenegotiate-request

                    if (string.IsNullOrEmpty(errorReason))
                    {
                        if (this.NegotiationResult.Url != null)
                        {
                            this.SetState(ConnectionStates.Redirected);

                            if (++this.RedirectCount >= this.Options.MaxRedirects)
                            {
                                errorReason = string.Format("MaxRedirects ({0:N0}) reached!", this.Options.MaxRedirects);
                            }
                            else
                            {
                                var oldUri = this.Uri;
                                this.Uri = this.NegotiationResult.Url;

                                if (this.OnRedirected != null)
                                {
                                    try
                                    {
                                        this.OnRedirected(this, oldUri, Uri);
                                    }
                                    catch (Exception ex)
                                    {
                                        HTTPManager.Logger.Exception("HubConnection", "OnNegotiationRequestFinished - OnRedirected", ex);
                                    }
                                }

                                StartConnect();
                            }
                        }
                        else
                        {
                            ConnectImpl();
                        }
                    }
                }
                else     // Internal server error?
                {
                    errorReason = string.Format("Negotiation Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                resp.StatusCode,
                                                resp.Message,
                                                resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                errorReason = "Negotiation Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                errorReason = "Negotiation Request Aborted!";
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                errorReason = "Negotiation Request - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                errorReason = "Negotiation Request - Processing the request Timed Out!";
                break;
            }

            if (errorReason != null)
            {
                SetState(ConnectionStates.Closed, errorReason);
            }
        }
        private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            HTTPManager.Logger.Information("EventSource", string.Format("OnRequestFinished - State: {0}, StatusCode: {1}", this.State, resp != null ? resp.StatusCode : 0), req.Context);

            if (this.State == States.Closed)
            {
                return;
            }

            if (this.State == States.Closing || req.IsCancellationRequested)
            {
                SetClosed("OnRequestFinished");

                return;
            }

            string reason = string.Empty;

            // In some cases retry is prohibited
            bool canRetry = true;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                // HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.
                if (resp.StatusCode == 200 && !resp.HasHeaderWithValue("content-type", "text/event-stream"))
                {
                    reason   = "No Content-Type header with value 'text/event-stream' present.";
                    canRetry = false;
                }

                // HTTP 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout responses, and any network error that prevents the connection
                //  from being established in the first place (e.g. DNS errors), must cause the user agent to asynchronously reestablish the connection.
                // Any other HTTP response code not listed here must cause the user agent to fail the connection.
                if (canRetry &&
                    resp.StatusCode != 500 &&
                    resp.StatusCode != 502 &&
                    resp.StatusCode != 503 &&
                    resp.StatusCode != 504)
                {
                    canRetry = false;

                    reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                // If the state is Closing, then it's a normal behaviour, and we close the EventSource
                reason = "OnRequestFinished - Aborted without request. EventSource's State: " + this.State;
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Processing the request Timed Out!";
                break;
            }

            // If we are not closing the EventSource, then we will try to reconnect.
            if (this.State < States.Closing)
            {
                if (!string.IsNullOrEmpty(reason))
                {
                    CallOnError(reason, "OnRequestFinished");
                }

                if (canRetry)
                {
                    Retry();
                }
                else
                {
                    SetClosed("OnRequestFinished");
                }
            }
            else
            {
                SetClosed("OnRequestFinished");
            }
        }
Ejemplo n.º 56
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("3-4-5"))
                {
                    //获取表头基本信息
                    sDate         = Utils.IsDateString(Utils.ChkSQL(HTTPRequest.GetString("dtime"))) ? DateTime.Parse(Utils.ChkSQL(HTTPRequest.GetString("dtime"))) : DateTime.Now;
                    InventoryName = HTTPRequest.GetString("InventoryName"); //盘点人
                    ManagerName   = HTTPRequest.GetString("ManagerName");   //仓管员
                    sTel          = HTTPRequest.GetString("sTel");
                    sAddress      = HTTPRequest.GetString("sAddress");


                    StorageID = HTTPRequest.GetInt("StorageID", 0);
                    ProductID = HTTPRequest.GetInt("ProductID", 0);
                    time      = HTTPRequest.GetString("sDate").Trim() != "" ? Convert.ToDateTime(HTTPRequest.GetString("sDate").Trim() + " 23:59:59") : DateTime.Now;

                    if (StorageID > 0)
                    {
                        si    = tbStorageInfo.GetStorageInfoModel(StorageID);
                        dList = tbProductsInfo.GetProductsStorageInfoByStorageID(0, StorageID, time, ProductID);
                    }
                    if (ispost)
                    {
                        reValue = HTTPRequest.GetString("reValue");//获取button提交过来的json值
                        if (sDate > DateTime.Now)
                        {
                            AddErrLine("盘点日期不能大于当前日期!");
                        }
                        else
                        {
                            storageName      = tbStockProductInfo.getSnameByScode(StorageID);
                            ms.SAppendTime   = sDate;
                            ms.SDateTime     = time;
                            ms.StorageID     = StorageID;
                            ms.StorageStaff  = ManagerName;
                            ms.StaffPhoneNum = sTel;
                            ms.StaffAdress   = sAddress;
                            ms.InventoryName = InventoryName;
                            ms.StaffID       = this.userinfo.StaffID;
                            ms.StaffName     = this.userinfo.uName;
                            ms.StorageName   = storageName;
                            try
                            {
                                info = tbStockProductInfo.getWarehouseInfo(StorageID, sDate);
                                if (info)
                                {
                                    AddMsgLine("数据重复,请核对后重新添加!");
                                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                                else
                                {
                                    ms.GetWarehouseDateJson = (GetWarehouseDateJsonList)JavaScriptConvert.DeserializeObject(reValue, typeof(GetWarehouseDateJsonList));
                                    bool state = tbStockProductInfo.AddWarehouseList(ms);
                                    if (state)
                                    {
                                        AddMsgLine("添加数据成功!");
                                        AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                    }
                                    else
                                    {
                                        AddMsgLine("添加数据失败!");
                                        AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                AddErrLine(ex.Message);
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
Ejemplo n.º 57
0
 public override void PrepareRequest(HTTPRequest request)
 {
     request.SetHeader("Content-Type", "application/x-www-form-urlencoded");
 }
Ejemplo n.º 58
0
        public int sType = -1;//发生类型,上岗=0,离岗=1

        protected virtual void Page_Load(object sender, EventArgs e)
        {
            pagesize = 20;
            PageBarHTML = "  ";
            string tSQL = " tbStaffStoresInfo.StaffStoresID<>0 ";

            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("4-2"))
                {
                    if (HTTPRequest.GetString("page").Trim() != "" && Utils.IsInt(HTTPRequest.GetString("page").Trim()))
                    {
                        pageindex = int.Parse(HTTPRequest.GetString("page").Trim());
                    }
                    else
                    {
                        pageindex = 1;
                    }
                    if (ispost)
                    {
                        Act = HTTPRequest.GetFormString("Act");
                        S_key = Utils.ChkSQL(HTTPRequest.GetFormString("S_key"));
                        StoresName = Utils.ChkSQL(HTTPRequest.GetFormString("StoresName"));
                        sType = HTTPRequest.GetFormInt("sType", -1);
                    }
                    else
                    {
                        Act = HTTPRequest.GetQueryString("Act");
                        S_key = Utils.ChkSQL(HTTPRequest.GetQueryString("S_key"));
                        StoresName = Utils.ChkSQL(HTTPRequest.GetQueryString("StoresName"));
                        sType = HTTPRequest.GetQueryInt("sType", -1);
                    }

                    if (Act.Trim() == "Search" && S_key.Trim() != "")
                    {
                        tSQL = tSQL + " and tbStaffStoresInfo.StaffID in (select StaffID from tbStaffInfo where tbStaffInfo.sName like'%" + S_key + "%') ";
                    }
                    if (Act.Trim() == "SearchB")
                    {

                    }
                    if (StoresName.Trim() != "")
                    {
                        tSQL = tSQL + " and tbStaffStoresInfo.StoresID in (select StoresID from tbStoresInfo where tbStoresInfo.sName like'%" + StoresName.Trim() + "%') ";
                    }
                    if (sType > -1)
                    {
                        tSQL = tSQL + " and tbStaffStoresInfo.sType=" + sType + " ";
                    }
                    if (Act.Trim() == "SearchB")
                    {
                        dList = tbStaffStoresInfo.GetStaff_StoresList(0, DateTime.Now.AddYears(-100), DateTime.Now, -1);

                        DataView view = new DataView();
                        view.Table = dList;
                        view.RowFilter = "edate > '" + DateTime.Now + "'";//离岗时间大于当前的
                        view.Sort = "StaffID DESC,StoresID DESC";
                        dList = view.ToTable();

                    }
                    else if (Act.Trim() == "SearchC")
                    {
                        dList = tbStaffStoresInfo.GetStaff_StoresList(0, DateTime.Now.AddYears(-100), DateTime.Now, -1);
                        DataView view = new DataView();
                        view.Table = dList;

                        view.Sort = "StaffID DESC,StoresID DESC";
                        dList = view.ToTable();
                    }
                    else
                    {
                        dList = tbStaffStoresInfo.GetStaffStoresInfoList(pagesize, pageindex, tSQL, out pagetotal, 1, "*,(select sName from tbStoresInfo where StoresID=tbStaffStoresInfo.StoresID) as StoresName,(select sName from tbStaffInfo where StaffID=tbStaffStoresInfo.StaffID) as StaffName");

                        PageBarHTML = Utils.TenPage(pageindex, pagetotal, 0, "&Act=" + Act + "&S_key=" + S_key + "&StoresName=" + StoresName + "&sType=" + sType);
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Prepares the request to sending a form. It should set only the headers.
 /// </summary>
 public virtual void PrepareRequest(HTTPRequest request)
 {
     throw new NotImplementedException();
 }
 public EventSourceResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache)
     : base(request, stream, isStreamed, isFromCache)
 {
     base.IsClosedManually = true;
 }