public ResponseInfo<Model.Customer> Register(Customer customer)
        {
            ResponseInfo<Model.Customer> response = new ResponseInfo<Customer>();

            if (customer == null)
            {
                return response;
            }

            bool result = CustomerBLL.Register(customer);

            if (result)
            {
                Model.Customer customerDetail = CustomerBLL.GetCustomerDetail(customer);

                response.Code = 1;
                response.Value = customerDetail;
            }
            else
            {
                response.Code = -1;
                response.Message = "注册用户已存在";
            }

            return response;
        }
        public ResponseInfo<Model.Customer> Login(Customer customer)
        {
            ResponseInfo<Model.Customer> response = new ResponseInfo<Customer>();

            if (customer == null)
            {
                return response;
            }

            bool result = CustomerBLL.Login(customer);

            if (result)
            {
                Model.Customer customerDetail = CustomerBLL.GetCustomerDetail(customer);

                response.Code = 1;
                response.Value = customerDetail;
            }
            else
            {
                response.Code = -1;
                response.Message = "用户名或密码错误";
            }

            return response;
        }
        public HarResponseInspector(ProxyResponse response, Entry entry)
        {
            _response = response;
            _entry = entry;

            var responseInfo = new ResponseInfo();
            _entry.Response = responseInfo;
        }
        private static Task Challenge(ResponseInfo response)
        {
            var challengeScheme = (response.Request.Headers.XRequestedWith != XMLHttpRequest ? Header.WWWAuthenticate : XWWWAuthenticate);
            response.Headers.Add(new Header(challengeScheme, String.Format("{0} realm=\"{1}\"", AuthenticationScheme, response.Request.Url.Host)));
            var accessControlExposeHeaders = response.Headers.AccessControlExposeHeaders ?? String.Empty;
            if (!String.IsNullOrEmpty(response.Request.Headers.Origin))
            {
                response.Headers.AccessControlExposeHeaders = accessControlExposeHeaders + (accessControlExposeHeaders.Length > 0 ? ", " : String.Empty) + challengeScheme;
            }

            response.Status = HttpStatusCode.Unauthorized;
            return Task.FromResult(0);
        }
Example #5
0
        public static ResponseInfo CreateLightStreamerResponse(string body)
        {
            var response = new ResponseInfo { Body = body };

            response.Headers["Content-Type"] = "text/plain; charset=iso-8859-1";
            response.Headers["Cache-Control"] = "no-cache";
            response.Headers["Pragma"] = "no-cache";
            response.Headers["Expires"] = "Thu, 1 Jan 1970 00:00:00 UTC";
            response.Headers["Server"] = "TestServer";
            response.Headers["Date"] = DateTime.UtcNow.ToString("R");
            if (!string.IsNullOrEmpty(body))
            {
                response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
            }
            return response;
        }
Example #6
0
    public ResponseInfo GetWebResponse(WebRequest webRequest)
    {
        try {
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            var responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
            responseText = responseText.Replace("\\", "");
            responseText = responseText.Substring(1, responseText.Length - 2);
            ResponseInfo responseInfo = JsonUtility.FromJson <ResponseInfo>(responseText);
            return(responseInfo);
        } catch (Exception e) {
            Debug.Log(e.Message);
            throw new Exception("Não foi receber resopsta do servidor");
        } finally {
            webRequest.Abort();
            StopCoroutine(checkAvailable);
        }
    }
Example #7
0
        public ResponseInfo <ResponseSODetails> GetSoListFromCust(RequestSODetailsFromCustAndSo data)
        {
            ResponseInfo <ResponseSODetails> response = new ResponseInfo <ResponseSODetails>();

            try
            {
                response.ResponseData = new ResponseSODetails();

                var listData = SODAL.GetSoListFromCust(data);

                response.ResponseData.sODetails = HelperUtil.GenerateSoDetailBase64String(listData);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(response);
        }
Example #8
0
        private void onTestsRecive(string data)
        {
            var response = ResponseInfo.FromJson(data);

            if (response.Error != null)
            {
                MessageBox.Show(CommandErrors.GetErrorMessage(response.Error), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                var tests = JsonConvert.DeserializeObject <List <string> >(SequrityUtils.DecryptString(response.Data, connection.User.SecretKey));
                listBoxTests.Items.Clear();
                foreach (var testName in tests)
                {
                    listBoxTests.Items.Add(testName);
                }
            }
        }
Example #9
0
 /// <summary>
 /// 提交一个零件明细(版本控制)
 /// 检查名称在库里是否存在,
 /// 1.若存在,则检查内容是否一致,不一致则不能提交,必须升级为新版本
 /// 2.不存在,则为新增,并检查版本号不能小于等于原有的版本号
 /// </summary>
 /// <param name="Part">零件明细</param>
 /// <returns></returns>
 public ResponseInfo SavePartVer(Part Part)
 {
     try
     {
         string _url = "/Part/PartFromUGVer";
         Part.FromUG = true;
         string       _return = _server.SendObject(_url, "NewPart", Part);
         ResponseInfo ri      = JsonConvert.DeserializeObject <ResponseInfo>(_return);
         return(ri);
     }
     catch (Exception ex)
     {
         return(new ResponseInfo()
         {
             Status = -1, Message = ex.Message
         });
     }
 }
Example #10
0
        private void putChunk(string upHost, long offset, int chunkSize, string context,
                              ProgressHandler progressHandler, CompletionHandler completionHandler)
        {
            int    chunkOffset = (int)(offset % Config.BLOCK_SIZE);
            string url         = string.Format("{0}/bput/{1}/{2}", upHost, context, chunkOffset);

            try
            {
                this.fileStream.Read(this.chunkBuffer, 0, chunkSize);
            }
            catch (Exception ex)
            {
                this.upCompletionHandler(this.key, ResponseInfo.fileError(ex), "");
                return;
            }
            this.crc32 = CRC32.CheckSumBytes(this.chunkBuffer, chunkSize);
            post(url, this.chunkBuffer, chunkSize, progressHandler, completionHandler);
        }
Example #11
0
        public ResponseInfo <ResponseSODetails> GetJobListFromDriver(RequestJobListFromDriver data)
        {
            ResponseInfo <ResponseSODetails> response = new ResponseInfo <ResponseSODetails>();

            try
            {
                response.ResponseData = new ResponseSODetails();
                var listData = EPODDAL.GetJobListFromDriver(data);

                response.ResponseData.sODetails = HelperUtil.GenerateSoDetailBase64String(listData);
            }
            catch (Exception ex)

            {
                throw ex;
            }
            return(response);
        }
Example #12
0
        public static ResponseInfo CreateLightStreamerResponse(string body)
        {
            var response = new ResponseInfo {
                Body = body
            };

            response.Headers["Content-Type"]  = "text/plain; charset=iso-8859-1";
            response.Headers["Cache-Control"] = "no-cache";
            response.Headers["Pragma"]        = "no-cache";
            response.Headers["Expires"]       = "Thu, 1 Jan 1970 00:00:00 UTC";
            response.Headers["Server"]        = "TestServer";
            response.Headers["Date"]          = DateTime.UtcNow.ToString("R");
            if (!string.IsNullOrEmpty(body))
            {
                response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
            }
            return(response);
        }
Example #13
0
        public static ResponseInfo CreateRpcResponse(string body)
        {

            var response = new ResponseInfo { Body = body };

            response.Headers["Cache-Control"] = "no-cache";
            response.Headers["Pragma"] = "no-cache";
            response.Headers["Content-Type"] = "text/json; charset=utf-8";
            response.Headers["Expires"] = "-1";
            response.Headers["Vary"] = "Accept-Encoding";
            response.Headers["Server"] = "TestServer";
            response.Headers["Date"] = DateTime.UtcNow.ToString("R");
            if (!string.IsNullOrEmpty(body))
            {
                response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
            }
            return response;
        }
        public ResponseInfo UpdateTheoDoi(int id, UpdateTheoDoi data)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response = new TheoDoiTruyenModel().UpadateTheoDoi(id, data);
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
Example #15
0
        /// <summary>
        /// Action kiểm tra tài khoản login bằng facebook của người dùng
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public JsonResult LoginByFB(string accessToken)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                SocialAccount account = new LoginModel().LayThongTinFB(accessToken);
                response.ThongTinBoSung1 = new LoginModel().CheckSocialAccount(account).Token;
            }
            catch (Exception e)
            {
                response.Code            = 500;
                response.MsgNo           = 100;
                response.ThongTinBoSung1 = e.Message;
            }

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
Example #16
0
        protected override void WriteLine(string message)
        {
            var rtbMessage = string.Format("{0:yy-MM-dd HH:mm:ss} {1}", DateTime.Now, message);

            if (!string.IsNullOrEmpty(message))
            {
                rtbLog.AppendText(rtbMessage);
                rtbLog.AppendText(Environment.NewLine);
            }

            if (tcpServer != null && !ServerWrite)
            {
                var info = ResponseInfo.Create(request, message);
                tcpServer.Send(tcpClient, Utils.Serialize(info));
            }

            System.Threading.Thread.Sleep(100);
        }
Example #17
0
        public ResponseInfo ThemPhanQuyen(NewPhanQuyen data)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response = new QuanLyPhanQuyenModel().ThemPhanQuyen(data);
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
        public async Task <ResponseInfo <List <LogDto> > > Handle(GetLogsQuery request, CancellationToken cancellationToken)
        {
            string path = request.FilePath + "\\Logs\\log" + request.Level + request.Date.ToString("yyyyMMdd") + ".txt";

            ResponseInfo <List <LogDto> > result = new ResponseInfo <List <LogDto> >
            {
                Data = new List <LogDto>()
            };

            if (!File.Exists(path))
            {
                result.ErrorMessage = path + " log dosyası bulunamadı.";
                return(result);
            }

            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8, false))
                {
                    string row = await streamReader.ReadLineAsync();

                    while (row != null)
                    {
                        result.Data.Add(JsonConvert.DeserializeObject <LogDto>(row));

                        row = await streamReader.ReadLineAsync();
                    }
                }
            }

            if (result.Data.Count == 0)
            {
                return(result);
            }

            result.TotalCount = result.Data.Count;

            if (request.Page != 0 && request.PageSize != 0)
            {
                result.Data = result.Data.Skip((request.Page - 1) * request.PageSize).Take(request.PageSize).ToList();
            }

            return(result);
        }
Example #19
0
        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var statusCode = HttpStatusCode.InternalServerError;

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)statusCode;

            ResponseInfo <object> result = new ResponseInfo <object>
            {
                Exception    = ex,
                ErrorMessage = ex.GetInnerExceptionMessage()
            };

            var responseBody = JsonConvert.SerializeObject(result);

            Log.Error(exception: ex, messageTemplate: responseBody);

            await context.Response.WriteAsync(responseBody);
        }
Example #20
0
        public ResponseInfo GetAllComicList()
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response.Data      = new HomeModel().GetDanhSachTruyen();
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
        public ResponseInfo TheoDoiTruyen(AddBookMark data)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                new TheoDoiTruyenModel().TheoDoiTruyen(data);
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
Example #22
0
 private static void GetInfoFromApp()
 {
     try
     {
         HttpWebRequest request =
             (HttpWebRequest)WebRequest.Create("http://localhost:9007/spareio/getInfo/");
         request.Method = "GET";
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
         {
             string str = string.Empty;
             if (response.StatusCode != HttpStatusCode.OK)
             {
                 LogWriter.InfoFormat(string.Format("Request failed. Received HTTP {0}", (object)response.StatusCode));
             }
             using (Stream responseStream = response.GetResponseStream())
             {
                 if (responseStream != null)
                 {
                     using (StreamReader streamReader = new StreamReader(responseStream))
                         str = streamReader.ReadToEnd();
                 }
             }
             object       abc      = new JavaScriptSerializer().Deserialize <object>(str);
             ResponseInfo jsonInfo = new JavaScriptSerializer().Deserialize <ResponseInfo>(abc.ToString());
             info = jsonInfo;
             _screenSaver.onBattery = Convert.ToInt32(info.SSBattery);
             _screenSaver.plugged   = Convert.ToInt32(info.SSPluggedIn);
             _displayOff.onBattery  = Convert.ToInt32(info.DOBattery);
             _displayOff.plugged    = Convert.ToInt32(info.DOPluggedIn);
             _inactivityCounterAvg  = Convert.ToDouble(info.InactivityCount);
             LogWriter.Info("_inactivityCounterAvg" + jsonInfo.InactivityCount);
         }
     }
     catch (Exception ex)
     {
         LogWriter.Error("Error while getting info from App" + ex.Message);
         _screenSaver.onBattery = 0;
         _screenSaver.plugged   = 0;
         _displayOff.onBattery  = 0;
         _displayOff.plugged    = 0;
         _inactivityCounterAvg  = 0;
     }
 }
Example #23
0
        public ResponseInfo Save(SuscripcionesDTO item)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO [Suscripciones] (Email, FechaSuscripcion, Estado) " +
                                                "VALUES (@Email, @FechaSuscripcion, @Estado)");
                cmd.CommandType = CommandType.Text;
                cmd.Connection  = con;
                cmd.Parameters.AddWithValue("@Email", item.Email);
                cmd.Parameters.AddWithValue("@FechaSuscripcion", DateTime.Now);
                cmd.Parameters.AddWithValue("@Estado", item.Estado);
                cmd.ExecuteNonQuery();
                con.Close();

                return(ResponseInfo.CreateSuccess());
            }
            catch (Exception ex) { return(ResponseInfo.CreateError("Error al grabar. " + ex.Message)); }
        }
Example #24
0
        public IActionResult OnPostRecords([FromBody] JObject reconcile)
        {
            //CreateReconciledate
            ReconcilePeriod _recondays = new ReconcilePeriod();

            ResponseInfo <ReconcilePeriod> responseInfo = new ResponseInfo <ReconcilePeriod>();

            if (!string.IsNullOrWhiteSpace(reconcile.ToString()))
            {
                foreach (var item in reconcile)
                {
                    Console.WriteLine(item.Key + " " + item.Value.ToString());

                    if (item.Key.ToString() == "accountID")
                    {
                        _recondays.AccountID = Convert.ToInt64(item.Value.ToString());
                    }
                    else if (item.Key.ToString() == "startDate")
                    {
                        _recondays.StartDate = DateTime.ParseExact(item.Value.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    }
                    else if (item.Key.ToString() == "endDate")
                    {
                        _recondays.EndDate = DateTime.ParseExact(item.Value.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    }
                    else if (item.Key.ToString() == "balance")
                    {
                        _recondays.Balance = Convert.ToDecimal(item.Value.ToString());
                    }
                    else if (item.Key.ToString() == "close")
                    {
                        _recondays.ClosingBal = Convert.ToDecimal(item.Value.ToString());
                    }
                    else if (item.Key.ToString() == "period")
                    {
                        _recondays.Period = item.Value.ToString();
                    }
                }

                responseInfo = _transactionRepository.CreateReconciledate(_recondays);
            }
            return(new JsonResult(responseInfo));
        }
Example #25
0
        public static ResponseInfo CreateRpcResponse(string body)
        {
            var response = new ResponseInfo {
                Body = body
            };

            response.Headers["Cache-Control"] = "no-cache";
            response.Headers["Pragma"]        = "no-cache";
            response.Headers["Content-Type"]  = "text/json; charset=utf-8";
            response.Headers["Expires"]       = "-1";
            response.Headers["Vary"]          = "Accept-Encoding";
            response.Headers["Server"]        = "TestServer";
            response.Headers["Date"]          = DateTime.UtcNow.ToString("R");
            if (!string.IsNullOrEmpty(body))
            {
                response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
            }
            return(response);
        }
Example #26
0
        public void ParseMessage(object sender, ResponseInfo e)
        {
            switch (e.Command)
            {
            case "login":
                OnLogonSuccess?.Invoke(this, JsonConvert.DeserializeObject <LoginClass>(e.Data));

                break;

            case "err":
                OnError?.Invoke(this, e.Data);

                break;

            default:

                break;
            }
        }
Example #27
0
        public ResponseInfo SearchComic(string query, int index)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response.Data      = new HomeModel().SearchComic(query, index);
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
        /// <summary>
        /// get an enumerable materializes the objects the response
        /// </summary>
        /// <param name="responseInfo">context</param>
        /// <param name="queryComponents">query components</param>
        /// <param name="plan">Projection plan (if compiled in an earlier query).</param>
        /// <param name="contentType">contentType</param>
        /// <param name="message">the message</param>
        /// <param name="expectedPayloadKind">expected payload kind.</param>
        /// <returns>atom materializer</returns>
        internal static MaterializeAtom Materialize(
            ResponseInfo responseInfo,
            QueryComponents queryComponents,
            ProjectionPlan plan,
            string contentType,
            IODataResponseMessage message,
            ODataPayloadKind expectedPayloadKind)
        {
            Debug.Assert(queryComponents != null, "querycomponents");
            Debug.Assert(message != null, "message");

            // If there is no content (For e.g. /Customers(1)/BestFriend is null), we need to return empty results.
            if (message.StatusCode == (int)HttpStatusCode.NoContent || String.IsNullOrEmpty(contentType))
            {
                return(MaterializeAtom.EmptyResults);
            }

            return(new MaterializeAtom(responseInfo, queryComponents, plan, message, expectedPayloadKind));
        }
        public ResponseInfo Get(int id)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response.Data      = new QuanLyTacGiaModel().LoadTacGia(id);
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
Example #30
0
        private void HandleFailure(ResponseInfo response)
        {
            string text = "none";

            if (response.TargetValue != null && response.TargetValue.Length > 0)
            {
                text = string.Join(", ", response.TargetValue);
            }
            string message = string.Format("Unable to update perimeter config: FaultId=<{0}>; FaultType=<{1}>; FaultDetail=<{2}>; Target=<{3}>; TargetValues=<{4}>", new object[]
            {
                response.Fault.Id,
                response.Status,
                response.Fault.Detail ?? "null",
                response.Target,
                text
            });

            base.WriteError(new InvalidOperationException(message), ErrorCategory.InvalidOperation, null);
        }
Example #31
0
        /// <summary>
        /// 从信息转换成模型
        /// </summary>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="response"></param>
        /// <returns></returns>
        private static ResponseInfo <TReturn> ConvertToResult <TReturn>(Task <HttpResponseMessage> response)
        {
            response.Wait();
            if (!response.Result.IsSuccessStatusCode)
            {
                throw new Exception("调用不成功!" + response.Result.StatusCode);
            }

            string resultstring = response.Result.Content.ReadAsStringAsync().Result;
            //resultstring=   resultstring.Replace("\"[", "[").Replace("]\"", "]");
            ResponseInfo <TReturn> result = null;

            if (!string.IsNullOrWhiteSpace(resultstring))
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseInfo <TReturn> >(resultstring);
            }

            return(result);
        }
        public ResponseInfo DanhSachTruyenVoiTacGia(int Id_TacGia)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response.Data      = new QuanLyTacGiaModel().GetListTruyenWithAuthor(Id_TacGia);
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
        public ResponseInfo UpdateAccount(UpdateAccount account)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response           = new InformationModel().UpdateAccount(account);
                response.IsSuccess = true;
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
Example #34
0
            protected override void Render(HtmlBlock.Block html)
            {
                ResponseInfo ri = Info("\'" + qinfo.GetQueueName() + "\' Queue Status").("Used Resources:"
                                                                                         , qinfo.GetUsedResources().ToString()).("Num Active Applications:", qinfo.GetNumActiveApplications
                                                                                                                                     ()).("Num Pending Applications:", qinfo.GetNumPendingApplications()).("Min Resources:"
                                                                                                                                                                                                           , qinfo.GetMinResources().ToString()).("Max Resources:", qinfo.GetMaxResources()
                                                                                                                                                                                                                                                  .ToString());
                int maxApps = qinfo.GetMaxApplications();

                if (maxApps < int.MaxValue)
                {
                    ri.("Max Running Applications:", qinfo.GetMaxApplications());
                }
                ri.(SteadyFairShare + ":", qinfo.GetSteadyFairShare().ToString());
                ri.(InstantaneousFairShare + ":", qinfo.GetFairShare().ToString());
                html.(typeof(InfoBlock));
                // clear the info contents so this queue's info doesn't accumulate into another queue's info
                ri.Clear();
            }
Example #35
0
        public ResponseInfo DanhSachPhanQuyenTheoTeam()
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                response.IsSuccess = true;
                response.Data      = new QuanLyPhanQuyenModel().DanhSachPhanQuyenTheoTeam();
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
            }
            return(response);
        }
Example #36
0
        private Response GetResponse(HttpStatusCode statusCode, NancyContext context)
        {
            var responseInfo = new ResponseInfo
            {
                StatusCode = (int)statusCode,
                Message    = statusCode.ToString(),
                Reason     = StaticConfiguration.DisableErrorTraces ? null : context.GetExceptionDetails()
            };
            var nonHtmlResponse = TryProcessNonHtml(responseInfo, context);

            if (nonHtmlResponse != null)
            {
                return(nonHtmlResponse);
            }
            var viewName = ((int)statusCode).ToString(CultureInfo.InvariantCulture);
            var response = _viewRenderer.RenderView(context, viewName);

            return(response);
        }
 /// <summary>
 /// Initializes a materializer context
 /// </summary>
 /// <param name="responseInfo">Response information used to initialize with the materializer</param>
 internal ODataMaterializerContext(ResponseInfo responseInfo)
 {
     this.ResponseInfo = responseInfo;
 }
Example #38
0
        /// <summary>
        /// This method is for parsing CUD operation payloads which are expected to contain one of the following:
        ///
        ///     - Single AtomEntry
        ///         This is the typical response we expect in the non-error case.
        ///     - Feed with a single AtomEntry
        ///         This is not valid per OData protocol, but we allowed this in V1/V2 and will continue to accept it since we can still treat it like a single entry.
        ///     - Error
        ///         Parser handles this case as we read the payload, it's not explicitly handled here.
        ///
        /// Since we don't control the payload, it may contain something that doesn't fit these requirements, in which case we will throw.
        /// </summary>
        /// <param name="reader">the reader for the payload</param>
        /// <param name="responseInfo">The current ResponseInfo object</param>
        /// <returns>the AtomEntry that was read</returns>
        internal static AtomEntry ParseSingleEntityPayload(XmlReader reader, ResponseInfo responseInfo)
        {
            using (AtomParser parser = new AtomParser(reader, AtomParser.XElementBuilderCallback, CommonUtil.UriToString(responseInfo.TypeScheme), responseInfo.DataNamespace, responseInfo.BaseUriResolver, responseInfo.MaxProtocolVersion))
            {
                Debug.Assert(parser.DataKind == AtomDataKind.None, "the parser didn't start in the right state");
                AtomEntry entry = null;
                while (parser.Read())
                {
                    if (parser.DataKind != AtomDataKind.Feed && parser.DataKind != AtomDataKind.Entry)
                    {
                        throw new InvalidOperationException(Strings.AtomParser_SingleEntry_ExpectedFeedOrEntry);
                    }

                    if (parser.DataKind == AtomDataKind.Entry)
                    {
                        if (entry != null)
                        {
                            throw new InvalidOperationException(Strings.AtomParser_SingleEntry_MultipleFound);
                        }

                        entry = parser.CurrentEntry;
                    }
                }

                if (entry == null)
                {
                    throw new InvalidOperationException(Strings.AtomParser_SingleEntry_NoneFound);
                }

                Debug.Assert(parser.DataKind == AtomDataKind.Finished, "the parser didn't end in the right state");
                return entry;
            }
        }
Example #39
0
        private void Listen()
        {
            while (_listen)
            {
                Socket socket;
                try
                {
                    socket = _listener.AcceptSocket();

                }
                catch (SocketException ex)
                {
                    if (ex.Message.Contains("A blocking operation was interrupted by a call to WSACancelBlockingCall"))
                    {
                        return;
                    }
                    throw;
                }


                if (socket.Connected)
                {
                    try
                    {
                        LogMessage("Socket connected");


                        var buffer = new Byte[_recieveBufferSize];
                        StringBuilder sb = new StringBuilder();
                        int count = -1;
                        string reqText;

                        count = socket.Receive(buffer, buffer.Length, 0);
                        reqText = Encoding.ASCII.GetString(buffer, 0, count);
                        sb.Append(reqText);
                        var pattern = new Regex("Content-Length: (?<length>\\d+)", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
                        int contentLength;
                        int bodyLength;
                        if (pattern.IsMatch(reqText))
                        {
                            contentLength = int.Parse(pattern.Match(reqText).Groups["length"].Value);
                            if (contentLength > 0)
                            {
                                int pos = reqText.IndexOf("\r\n\r\n");

                                bodyLength = reqText.Length - (pos + 4);
                                while (bodyLength < contentLength)
                                {

                                    count = socket.Receive(buffer, buffer.Length, 0);
                                    reqText = Encoding.ASCII.GetString(buffer, 0, count);
                                    bodyLength = bodyLength + reqText.Length;
                                    sb.Append(reqText);
                                }

                            }
                        }

                        reqText = sb.ToString();
                        LogMessage("SERVER RECEVIED:\n" + reqText);



                        var request = new RequestInfo(reqText);


                        ResponseInfo response = HandleRequest(request);

                        byte[] responseBytes = Encoding.ASCII.GetBytes(response.ToString());

                        WriteToSocket(responseBytes, ref socket);
                        LogMessage("SERVER SENT:\n" + response.ToString());
                    }
                    catch (Exception ex)
                    {

                        ResponseInfo response = new ResponseInfo()
                                                    {
                                                        Body = ex.ToString(),
                                                        Status = "503 Internal Server Error"
                                                    };
                        byte[] responseBytes = Encoding.ASCII.GetBytes(response.ToString());
                        WriteToSocket(responseBytes, ref socket);
                        LogMessage("SERVER SENT:\n" + response.ToString());

                    }
                    socket.Close();
                    LogMessage("Socket Closed");
                }
            }

        }
Example #40
0
        private static ResponseInfo SendData(
            bool returnBytes,
            string method,
            string url,
            PostContentData[] postDatas = null,
            FileContentData[] fileDatas = null,
            HeaderData[] headers = null,
            string userAgent = null,
            NetworkCredential credential = null,
            ProxySettings proxySettings = null,
            int timeout = TIMEOUT,
            int maxAttempts = CONNECTION_ATTEMPTS,
            bool getResponse = true
            )
        {
            ResponseInfo result = null;

            int attempts = 0;
            bool success = false;
            string message = null;

            // Try to send data for number of connectionAttempts
            while (attempts < maxAttempts && !success)
            {
                attempts += 1;

                try
                {
                    // Create HTTP request and define Header info
                    var request = (HttpWebRequest)WebRequest.Create(url);

                    string boundary = String_Functions.RandomString(10);

                    request.Timeout = timeout;
                    request.ReadWriteTimeout = timeout;
                    if (method == "POST") request.ContentType = "multipart/form-data; boundary=" + boundary;
                    else request.ContentType = "application/x-www-form-urlencoded";

                    // Set the Method
                    request.Method = method;

                    // Set the UserAgent
                    if (userAgent != null) request.UserAgent = userAgent;
                    else request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                    // Add Header data to request stream (if present)
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            request.Headers[header.Id] = header.Text;
                        }
                    }

                    // set NetworkCredentials
                    if (credential != null)
                    {
                        request.Credentials = credential;
                        request.PreAuthenticate = true;
                    }

                    // Get Default System Proxy (Windows Internet Settings -> Proxy Settings)
                    var proxy = WebRequest.GetSystemWebProxy();

                    // Get Custom Proxy Settings from Argument (overwrite default proxy settings)
                    if (proxySettings != null)
                    {
                        if (proxySettings.Address != null && proxySettings.Port > 0)
                        {
                            var customProxy = new WebProxy(proxySettings.Address, proxySettings.Port);
                            customProxy.BypassProxyOnLocal = false;
                            proxy = customProxy;
                        }
                    }

                    request.Proxy = proxy;

                    var bytes = new List<byte>();

                    // Add Post Name/Value Pairs
                    if (postDatas != null)
                    {
                        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                        foreach (var postData in postDatas)
                        {
                            string formitem = string.Format(formdataTemplate, postData.Name, postData.Value);

                            bytes.AddRange(GetBytes("\r\n--" + boundary + "\r\n"));
                            bytes.AddRange(GetBytes(formitem));
                        }
                    }

                    // Add File data
                    if (fileDatas != null)
                    {
                        bytes.AddRange(GetFileContents(fileDatas, boundary));
                    }

                    if (bytes.Count > 0)
                    {
                        // Write Trailer Boundary
                        string trailer = "\r\n--" + boundary + "--\r\n";
                        bytes.AddRange(GetBytes(trailer));

                        var byteArray = bytes.ToArray();

                        // Write Data to Request Stream
                        request.ContentLength = byteArray.Length;

                        using (var requestStream = request.GetRequestStream())
                        {
                            requestStream.Write(byteArray, 0, byteArray.Length);
                        }
                    }

                    // Get Response Message from HTTP Request
                    if (getResponse)
                    {
                        result = new ResponseInfo();

                        using (var response = (HttpWebResponse)request.GetResponse())
                        {
                            // Get HTTP Response Body
                            using (var responseStream = response.GetResponseStream())
                            using (var memStream = new MemoryStream())
                            {
                                byte[] buffer = new byte[10240];

                                int read;
                                while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    memStream.Write(buffer, 0, read);
                                }

                                result.Body = memStream.ToArray();

                                success = true;
                            }

                            var responseHeaders = new List<ReponseHeaderInfo>();

                            // Get HTTP Response Headers
                            foreach (var key in response.Headers.AllKeys)
                            {
                                var header = new ReponseHeaderInfo();
                                header.Key = key;
                                header.Value = response.Headers.Get(key);

                                responseHeaders.Add(header);
                            }

                            result.Headers = responseHeaders.ToArray();
                        }
                    }
                    else success = true;
                }
                catch (WebException wex) { message = wex.Message; }
                catch (Exception ex) { message = ex.Message; }

                if (!success) System.Threading.Thread.Sleep(500);
            }

            if (!success) Logger.Log("Send :: " + attempts.ToString() + " Attempts :: URL = " + url + " :: " + message);

            return result;
        }
Example #41
0
 public HttpResult(ResponseInfo respInfo, string response)
 {
     this.ResponseInfo = respInfo;
     this.Response = response;
 }