Exemplo n.º 1
0
        public ActionResult CompressImage(string image)
        {
            string path = Server.MapPath("~/" + image);

            RequestUtil req = new RequestUtil();
            byte[] buffer = ImageUtil.Compress(path, req.Int("w", defaultValue: 174));

            return File(buffer, "image/jpeg");
        }
Exemplo n.º 2
0
        public ActionResult Messages(int id, int?idUser)
        {
            List <MessageResponse> messages = new List <MessageResponse>();

            MessageRequest messageRequest = new MessageRequest();

            messageRequest.IdRoom = id;
            messageRequest.IdUser = idUser ?? 0;

            RequestUtil request = new RequestUtil();
            Reply       reply   = request.Execute <MessageRequest>(AppSettings.Url.MESSAGES, "post", messageRequest);

            messages = JsonConvert.DeserializeObject <List <MessageResponse> >(JsonConvert.SerializeObject(reply.Data));

            messages = messages.OrderBy(d => d.DateCreated).ToList();

            ViewBag.idRoom = id;

            return(View(messages));
        }
Exemplo n.º 3
0
        /**
         * 创建一个腾讯云连接
         * @param action
         * @param apiAddr
         * @param urlArgs
         * @return 接口返回
         */
        private RestRequestAsyncHandle createTenAccess <T>(String action, String apiAddr, SortedDictionary <string, string> urlArgs, Action <IRestResponse <T> > callBackActoin) where T : new()
        {
            if (null == urlArgs)
            {
                urlArgs = new SortedDictionary <string, string>(StringComparer.Ordinal);
            }
            var nonce = RandomUtil.MakeSring(false, 6);

            PutUrlArg(urlArgs, "Action", action);
            PutUrlArg(urlArgs, "Timestamp", TimeUtil.CurrentMillis() / 1000 + "");
            PutUrlArg(urlArgs, "Nonce", nonce);
            PutUrlArg(urlArgs, "SecretId", mTenDnsApiSecret.SecretId);

            var signature = createSignature("POST", apiAddr, urlArgs);

            PutUrlArg(urlArgs, "Signature", signature);
            return(RequestUtil.AsyncRequest <T>(PROTOCOL + CNS_DOMAIN + apiAddr, urlArgs, callBackActoin, Method.POST));
            //restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
            //return restTemplate.postForObject(PROTOCOL + CNS_DOMAIN + apiAddr, convertMap(urlArgs), JSONObject.class);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Updates the comments on the specified discussion.
        /// </summary>
        /// <param name="discussion">The discussion with comments to update.</param>
        /// <param name="options">The options to apply before executing the REST API call.</param>
        /// <returns>
        /// A <see cref="DiscussionState"/> instance containing the REST API response.
        /// </returns>
        protected DiscussionState UpdateComments(Discussion discussion, params IStateTransitionOption[] options)
        {
            String target = GetSelfUri();
            Link   link   = GetLink(Rel.COMMENTS);

            if (link != null && link.Href != null)
            {
                target = link.Href;
            }

            FamilySearchPlatform gx = new FamilySearchPlatform();

            gx.Discussions = new List <Discussion>()
            {
                discussion
            };
            IRestRequest request = RequestUtil.ApplyFamilySearchConneg(CreateAuthenticatedRequest()).SetEntity(gx).Build(target, Method.POST);

            return(((FamilySearchStateFactory)this.stateFactory).NewDiscussionState(request, Invoke(request, options), this.Client, this.CurrentAccessToken));
        }
Exemplo n.º 5
0
        // GET: Lobby
        public ActionResult Index()
        {
            GetSession();

            List <ListRoomsResponce> lst = new List <ListRoomsResponce>();

            SecurityRequest oSecurityRequest = new SecurityRequest();

            oSecurityRequest.AccessToken = oUserSession.AccessToken;

            RequestUtil oRequestUtil = new RequestUtil();

            UtilitiesChat.Models.WS.Reply oReply = oRequestUtil.Execute <SecurityRequest>(Constants.Url.ROOMS, "post", oSecurityRequest);

            lst = JsonConvert.DeserializeObject <List <ListRoomsResponce> >(
                JsonConvert.SerializeObject(oReply.data)
                );

            return(View(lst));
        }
Exemplo n.º 6
0
        public ResponseModel <UserModel> UserSignup([FromBody] UserModel user)
        {
            user.IsNull();
            user.Validate(true);

            var reqHeader = RequestUtil.GetRequestHeader(Request);
            var password  = user.Password;

            using (var uow = UnitOfWork.Initialize())
            {
                IsNullUOW(uow);
                string message = uow.UserRepository.Add(reqHeader, user);
                if (string.IsNullOrEmpty(message))
                {
                    uow.Commit();
                }

                return(CreateResponse(message, user));
            }
        }
Exemplo n.º 7
0
        // GET: Lobby
        public ActionResult Index()
        {
            GetSession();
            List <ListRoomResponse> lst = new List <ListRoomResponse>();

            //oUserSession

            SecurityRequest oSecurityRequest = new SecurityRequest();

            oSecurityRequest.AccessToken = oUserSession.AccessToken;
            Reply       oReply       = new Reply();
            RequestUtil oRequestUtil = new RequestUtil();

            oReply = oRequestUtil.Execute <SecurityRequest>(Constants.Url.Rooms, "post", oSecurityRequest);
            JavaScriptSerializer js = new JavaScriptSerializer();

            lst = js.Deserialize <List <ListRoomResponse> >(js.Serialize(oReply.data));

            return(View(lst));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds a child and parents relationship to the collection.
        /// </summary>
        /// <param name="chap">The child and parent relationship to add.</param>
        /// <param name="options">The options to apply before executing the REST API call.</param>
        /// <returns>
        /// A <see cref="ChildAndParentsRelationshipState"/> instance containing the REST API response.
        /// </returns>
        /// <exception cref="Gx.Rs.Api.GedcomxApplicationException">Thrown if a link to the required resource cannot be found.</exception>
        public ChildAndParentsRelationshipState AddChildAndParentsRelationship(ChildAndParentsRelationship chap, params IStateTransitionOption[] options)
        {
            Link link = GetLink(Rel.RELATIONSHIPS);

            if (link == null || link.Href == null)
            {
                throw new GedcomxApplicationException(String.Format("FamilySearch Family Tree at {0} didn't provide a 'relationships' link.", GetUri()));
            }

            FamilySearchPlatform entity = new FamilySearchPlatform();

            entity.ChildAndParentsRelationships = new List <ChildAndParentsRelationship>()
            {
                chap
            };
            IRestRequest request = RequestUtil.ApplyFamilySearchConneg(CreateAuthenticatedRequest()).Build(link.Href, Method.POST);

            request.SetEntity(entity);
            return(((FamilyTreeStateFactory)this.stateFactory).NewChildAndParentsRelationshipState(request, Invoke(request, options), this.Client, this.CurrentAccessToken));
        }
Exemplo n.º 9
0
        private void GetMessages()
        {
            int idRoom = 0;

            //posYFinal = 10;
            panelMessages.Controls.Clear();
            lastPanel = null;
            try
            {
                idRoom = (int)cboRooms.SelectedValue;
            }
            catch (Exception ex)
            {
                // throw;
            }


            if (idRoom > 0)
            {
                List <MessagesResponse> lst = new List <MessagesResponse>();

                MessagesRequest oMessagesRequest = new MessagesRequest();
                oMessagesRequest.AccessToken = Business.Session.oUser.AccessToken;
                oMessagesRequest.idRoom      = idRoom;

                Reply oReply = new Reply();

                RequestUtil oRequestUtil = new RequestUtil();

                oReply = oRequestUtil.Execute <SecurityRequest>(Constants.Url.Messages, "post", oMessagesRequest);
                JavaScriptSerializer js = new JavaScriptSerializer();
                lst = js.Deserialize <List <MessagesResponse> >(js.Serialize(oReply.data));
                lst = lst.OrderBy(d => d.DateCreated).ToList();


                foreach (MessagesResponse oMessage in lst)
                {
                    AddMessage(oMessage);
                }
            }
        }
Exemplo n.º 10
0
        public void Extract(HttpRequest request, PageType page)
        {
            string valueString = RequestUtil.GetParameter(HttpContext.Current, this.Name);

            if (string.IsNullOrEmpty(valueString))
            {
                if (this.Required)
                {
                    throw new ApplicationException("The parameter \"{0}\" is required but was not supplied.".FormatString(this.Name));
                }
            }
            else
            {
                if (this.Validator != null && !this.Validator(valueString))
                {
                    throw new ApplicationException("The parameter \"{0}\" is not valid.".FormatString(this.Name));
                }

                this.Extractor(valueString, page);
            }
        }
Exemplo n.º 11
0
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            var    session   = HttpContext.Current.Session;
            string ipaddress = string.Empty;

            if (actionContext.Request.Properties.ContainsKey("MS_HttpContext"))
            {
                ipaddress = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            }
            else if (actionContext.Request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                RemoteEndpointMessageProperty prop;
                prop      = (RemoteEndpointMessageProperty)actionContext.Request.Properties[RemoteEndpointMessageProperty.Name];
                ipaddress = prop.Address;
            }

            if (IsPreLoginRequest(actionContext))
            {
                return;
            }

            if (session["authinfo"] == null)
            {
                string localURL = actionContext.Request.RequestUri.LocalPath.ToLower();
                string method   = RequestUtil.GetAction(localURL);
                if (!localURL.ToLower().EndsWith("SaveFBDetails".ToLower()) &&
                    !localURL.ToLower().EndsWith("Register".ToLower()) &&
                    !localURL.ToLower().EndsWith("Login".ToLower()))
                {
                    throw new AppException(ErrorCode.INVALID_SESSION);
                }
            }
            else
            {
                ResetAppRequestContext(session, ipaddress);
            }
        }
Exemplo n.º 12
0
        public ActionResult Messages(int id)
        {
            GetSession();

            List <MessagesResponse> lst = new List <MessagesResponse>();

            MessagesRequest oMessagesRequest = new MessagesRequest();

            oMessagesRequest.AccessToken = oUserSession.AccessToken;
            oMessagesRequest.IdRoom      = id;

            RequestUtil oRequestUtil = new RequestUtil();
            Reply       oReply       = oRequestUtil.Execute <MessagesRequest>(Constants.Url.MESSAGES, "post", oMessagesRequest);

            lst = JsonConvert.DeserializeObject <List <MessagesResponse> >(JsonConvert.SerializeObject(oReply.data));

            lst = lst.OrderBy(d => d.DateCreated).ToList();

            ViewBag.idRoom = id;

            return(View(lst));
        }
Exemplo n.º 13
0
    public override async Task <AccessCredentials> GetCredentialsAsync()
    {
        if (Credentials != null && !Credentials.AreExpired())
        {
            Credentials = Credentials;
            return(Credentials);
        }

        var url          = CustomEndPoint;
        var awsTokenFile = Environment.GetEnvironmentVariable("AWS_WEB_IDENTITY_TOKEN_FILE");

        if (!string.IsNullOrWhiteSpace(awsTokenFile))
        {
            Credentials = GetAccessCredentials(awsTokenFile);
            return(Credentials);
        }

        var containerRelativeUri = Environment.GetEnvironmentVariable("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI");
        var containerFullUri     = Environment.GetEnvironmentVariable("AWS_CONTAINER_CREDENTIALS_FULL_URI");
        var isURLEmpty           = url == null;

        if (!string.IsNullOrWhiteSpace(containerRelativeUri) && isURLEmpty)
        {
            url = RequestUtil.MakeTargetURL("169.254.170.2" + "/" + containerRelativeUri, false);
        }
        else if (!string.IsNullOrWhiteSpace(containerFullUri) && isURLEmpty)
        {
            var fullUri = new Uri(containerFullUri);
            url = RequestUtil.MakeTargetURL(fullUri.AbsolutePath, fullUri.Scheme == "https");
        }
        else
        {
            url = await GetIamRoleNamedURL();
        }

        Credentials = await GetAccessCredentials(url);

        return(Credentials);
    }
Exemplo n.º 14
0
        public InvokeResult <ImageRepoUploadResult> Upload(ImageRepoUploadArg arg)
        {
            var apiType = CHANNELS[RandomUtil.GetRangeRandomNum(0, CHANNELS.Length)];
            ImageRepoUploadResult apiResult = new ImageRepoUploadResult()
            {
                Api        = GetApiCode(),
                ApiChannel = apiType
            };
            //执行上传
            //var uploadFileFormName = "sheet_" + RandomUtil.makeSring(false, 8) + ".png";
            var response = RequestUtil.UploadFile("https://image.kieng.cn/upload.html?type=" + apiType, arg.FullFilePath, "image", arg.ExtraArgs["uploadFileFormName"].ToString(), null);

            if (string.IsNullOrEmpty(response))
            {
                return(new InvokeResult <ImageRepoUploadResult>()
                {
                    success = false,
                    message = "请求无返回"
                });
            }
            //转换为json对象
            JObject resultModel = (JObject)JsonConvert.DeserializeObject(response);
            int     code        = Convert.ToInt32(resultModel["code"]);

            if (code != 200)
            {
                return(new InvokeResult <ImageRepoUploadResult>()
                {
                    success = false,
                    message = "[" + apiType + "]" + Convert.ToString(resultModel["msg"])
                });
            }
            apiResult.ImgUrl = resultModel["data"]["url"].ToString();
            return(new InvokeResult <ImageRepoUploadResult>()
            {
                success = true,
                data = apiResult
            });
        }
Exemplo n.º 15
0
        private List <WorkItemDTO> processQuery(QueryDTO query)
        {
            List <WorkItemDTO> lstWork = new List <WorkItemDTO>();
            var result = RequestUtil.Post(workItemQuery, JsonConvert.SerializeObject(query), null, CredentialCache.DefaultCredentials);
            WorkItemQueryResult             qRes = JsonConvert.DeserializeObject <WorkItemQueryResult>(result);
            IEnumerable <WorkItemReference> workItemRefs;
            int skip = 0, qtd = 5;

            do
            {
                workItemRefs = qRes.WorkItems.Skip(skip).Take(qtd);
                if (workItemRefs.Any())
                {
                    string url     = string.Format(workitemIds, string.Join(",", workItemRefs.Select(t => t.Id).ToList()));
                    var    resultW = RequestUtil.Get(url, null, CredentialCache.DefaultCredentials);
                    var    lstAux  = JsonConvert.DeserializeObject <TfsDefault <WorkItem> >(resultW);
                    lstAux.value.ForEach(t => lstWork.Add(new WorkItemDTO(t)));
                }
                skip += qtd;
            }while (workItemRefs.Count() == qtd);
            return(lstWork);
        }
Exemplo n.º 16
0
        public static bool CheckAuth(out int uid)
        {
            RequestUtil req     = new RequestUtil();
            string      account = req.String("account", false, "授权错误");
            string      auth    = req.String("auth", false, "授权错误");

            if (req.HasError)
            {
                Json.Write(new { success = false, returnCode = "0000", msg = req.FirstError, errors = req.GetErrors() }, HttpContext.Current.Response.Output);
            }
            else if (CheckAuth(account, auth))
            {
                uid = GetAccountID(account);
                return(true);
            }
            else
            {
                Json.Write(new { success = false, returnCode = "0000", msg = "授权错误" }, HttpContext.Current.Response.Output);
            }
            uid = 0;
            return(false);
        }
Exemplo n.º 17
0
        //Get the expression tree
        public static String ProcessExpressionTree(Workspace w, QueryTreeInfo queryTreeInfo)
        {
            // Retrieve expression tree.
            AstoriaResponse rs;

            RequestUtil.GetAndVerifyStatusCode(w, w.ServiceUri + "/ExpToXml", HttpStatusCode.OK, out rs);
            if (rs.ActualStatusCode != HttpStatusCode.OK && rs.ActualStatusCode != HttpStatusCode.NotFound)
            {
                AstoriaTestLog.WriteLine("/ExpToXml returned error code " + rs.ActualStatusCode.ToString() + ", payload:");
                AstoriaTestLog.FailAndThrow(rs.Payload);
            }

            // Extract XML document from response.
            XmlDocument xml = new XmlDocument();

            xml.LoadXml(rs.Payload);

            // Skip verification in retail builds as they do not contain expression capture hook.
            string embeddedDocument = xml.DocumentElement.InnerText;

            AstoriaTestLog.WriteLine(embeddedDocument);
            if (embeddedDocument.StartsWith("WARNING"))
            {
                // Warn the user.
                AstoriaTestLog.WriteLine("WARNING: missing expression tree!");
                AstoriaTestLog.Skip("Test variation skipped");
            }

            // Separate string form and XML form.
            string[] pair = embeddedDocument.Split(new string[] { "[[===]]" }, StringSplitOptions.None);
            xml.LoadXml(pair[1].Replace("utf-16", "utf-8"));
            AstoriaTestLog.WriteLine(xml.OuterXml);
            if (queryTreeInfo != null)
            {
                queryTreeInfo.currentTreeXml = xml;
            }
            //return xml;
            return(pair[0]);
        }
Exemplo n.º 18
0
        // GET: Chat
        public ActionResult Messages(int id)
        {
            GetSession();
            List <MessagesResponse> lst = new List <MessagesResponse>();

            MessagesRequest oMessagesRequest = new MessagesRequest();

            oMessagesRequest.AccessToken = oUserSession.AccessToken;
            oMessagesRequest.idRoom      = id;

            Reply oReply = new Reply();

            RequestUtil oRequestUtil = new RequestUtil();

            oReply = oRequestUtil.Execute <SecurityRequest>(Constants.Url.Messages, "post", oMessagesRequest);
            JavaScriptSerializer js = new JavaScriptSerializer();

            lst            = js.Deserialize <List <MessagesResponse> >(js.Serialize(oReply.data));
            lst            = lst.OrderBy(d => d.DateCreated).ToList();
            ViewBag.IdRoom = id;
            return(View(lst));
        }
Exemplo n.º 19
0
        public void TestIfDomainIsValid()
        {
            Dictionary <string, bool> testDomainDict = new Dictionary <string, bool>
            {
                { "%$$$", false },
                { "s3.amazonaws.com", true },
                { "s3.cn-north-1.amazonaws.com.cn", true },
                { "s3.amazonaws.com_", false },
                { "s3.amz.test.com", true },
                { "s3.%%", false },
                { "localhost", true },
                { "-localhost", false },
                { "", false },
                { "\n \t", false },
                { "   ", false },
            };

            foreach (KeyValuePair <string, bool> testCase in testDomainDict)
            {
                Assert.AreEqual(RequestUtil.IsValidEndpoint(testCase.Key), testCase.Value);
            }
        }
        /// <summary>
        /// Wrapper of <see cref="HttpClientHandler.SendAsync"/> method.
        /// It collects information from request and response. Also, a trace header will be injected
        /// into the HttpWebRequest to propagate the tracing to downstream web service.
        /// </summary>
        /// <param name="request">An instance of <see cref="HttpResponseMessage"/></param>
        /// <param name="cancellationToken">An instance of <see cref="CancellationToken"/></param>
        /// <returns>A Task of <see cref="HttpResponseMessage"/> representing the asynchronous operation</returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            RequestUtil.ProcessRequest(request);
            HttpResponseMessage response;

            try
            {
                response = await base.SendAsync(request, cancellationToken);

                RequestUtil.ProcessResponse(response);
            }
            catch (Exception ex)
            {
                AWSXRayRecorder.Instance.AddException(ex);
                throw;
            }
            finally
            {
                AWSXRayRecorder.Instance.EndSubsegment();
            }
            return(response);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 爬取IP
        /// </summary>
        private void StartCrawlIP(object state)
        {
            var taskName  = "\n[ 抓取IP任务 ]";
            var crawRules = GetCrawlRules();

            //遍历所有规则
            crawRules.ForEach(item =>
            {
                //对每一条规则单开一个线程
                Task.Run(() => {
                    //设置爬取的页数, 以第一页为当前页
                    for (var currentPage = 1; currentPage <= item.MaxPage; currentPage++)
                    {
                        var curTaskDesc = string.Format("{0} 规则 -> {1} ", taskName, item.Name);
                        //请求目标地址, 获取目标地址HTML
                        var crawlResult = RequestUtil.CrawlContentFromWebsit(string.Format(item.Url, currentPage), null);
                        if (!crawlResult.success)
                        {
                            mEventLog.WriteEntry(curTaskDesc + (curTaskDesc + "页面抓取失败"));
                            continue;
                        }
                        //设置匹配规则
                        Match mstr = Regex.Match(crawlResult.data, item.Partten);
                        mEventLog.WriteEntry(curTaskDesc + (mstr.Success ? "匹配成功" : "匹配失败"));
                        //开始逐行爬取IP
                        while (mstr.Success)
                        {
                            var proxyAddress = mstr.Groups[1].Value + ":" + mstr.Groups[2].Value;
                            mstr             = mstr.NextMatch();
                            if (IsProxyValid(proxyAddress))
                            {
                                SaveProxyToDB(proxyAddress);
                            }
                        }
                    }
                });
            });
        }
Exemplo n.º 22
0
 public async Task <IActionResult> Import()
 {
     try
     {
         var fileToProcess = Request.Form.Files.FirstOrDefault();
         var filePath      = Path.Combine(Directory.GetCurrentDirectory(), "UploadFiles", DateTime.Now.ToString("yyyyMMdd"), fileToProcess.FileName);
         var fileDirectory = Path.GetDirectoryName(filePath);
         if (!Directory.Exists(fileDirectory))
         {
             Directory.CreateDirectory(fileDirectory);
         }
         if (fileToProcess != null && fileToProcess.Length > 0)
         {
             using (var inputStream = new FileStream(filePath, FileMode.Create))
             {
                 // read file to stream
                 await fileToProcess.CopyToAsync(inputStream);
             }
             DataTable dtBackData = ExcelHelper.Import(filePath);
             var       orders     = OrderInfo.FromDataTable(dtBackData);
             foreach (var order in orders)
             {
                 var orderJson  = JsonConvert.SerializeObject(order);
                 var orderBytes = Encoding.UTF8.GetBytes(orderJson);
                 await RequestUtil.DoRequestWithBytesPostDataAsync(_processApiUrl, "post", "application/json", 60 * 1000, 60 * 1000 * 3, orderBytes);
             }
             ;
         }
         return(Ok());
     }
     catch (Exception ex)
     {
         _logger.Error(ex.ToString());
         return(BadRequest(ex.Message));
     }
 }
Exemplo n.º 23
0
        public void GetPlatform_Test()
        {
            var userAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
            var actual    = RequestUtil.GetPlatform(userAgent);

            Assert.Equal("Windows", actual);
            Assert.False(RequestUtil.IsWechatPlatform(userAgent));
            Assert.True(RequestUtil.IsWechatPlatform("aasda MicroMessenger xxxxx"));

            Assert.False(RequestUtil.IsMobile(userAgent));

            var android = RequestUtil.GetPlatform("Android xxxxx");

            Assert.Equal("Android", android);
            var iphone = RequestUtil.GetPlatform("xxxx iphone IPad qqqqqqxxxxaqss");

            Assert.Equal("IPhone", iphone);
            var mac = RequestUtil.GetPlatform("xxxx macintosh  xx");

            Assert.Equal("MacBook", mac);

            Assert.Equal("", RequestUtil.GetPlatform("xxxx xx  xx"));
            Assert.Equal("", RequestUtil.GetPlatform(""));
        }
Exemplo n.º 24
0
        public MainWindow()
        {
            InitializeComponent();

            string         html;
            SessionManager sm = SessionManager.GetInstance();

            sm.Email    = ""; // set email before running
            sm.Password = ""; // set password before running

            RequestUtil request = RequestUtil.NewInstance("https://leaderboards.guildwars2.com", "/en/na/achievements/guild/Guíld%20Of%20Dívíne%20Soldíers");

            request.SetMethod(Method.GET);
            request.SetCookie("s", sm.Session.Key);
            IRestResponse r = request.Execute();

            html = r.Content;

            List <user> l = ParseUserPage(html);

            TextArea.FontFamily = new FontFamily("Courier New");
            TextArea.Text       = string.Format("{0,-20} | {1,-6} | {2,-20} | {3}\n{4}", "User", "AP", "World", "Last Earned AP",
                                                string.Join("\n", l.Select(u => string.Format("{0,-20} | {1,6} | {2,-20} | {3}", u.account, u.ap, u.world, u.lastapgain))));
        }
Exemplo n.º 25
0
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (inited == false)
            {
                #region 初始化

                lock (initLocker)
                {
                    if (inited == false)
                    {
                        LogHelper.CreateDebugLog("bbsmax 开始初始化");

                        Config.Current = new WebEngineConfig();
                        TemplateManager.Init(false); //TODO:重复执行会出错

                        //初始化系统并载入设置
                        Globals.Init();
                        Booter.Init();  //TODO:重复执行会出错

                        //初始化插件
                        PluginManager.Init();

#if !Passport
                        //将最后一次备份的在线信息恢复至内存
                        OnlineUserPool.Instance.Restore();
#endif

                        //初始化路由
                        BbsRouter.Init();

                        inited = true;
                    }
                }

                #endregion
            }

            if (Request.RequestType == "POST")
            {
                #region 处理大文件上传

                if (StringUtil.StartsWithIgnoreCase(Request.RawUrl, Globals.AppRoot + "/default.aspx?uploadtempfile.aspx"))
                {
                    string query = Request.RawUrl.Substring(Globals.AppRoot.Length + 33);

                    new MaxLabs.bbsMax.AppHandlers.UploadTempFileHandler().ProcessRequest(HttpContext.Current, HttpUtility.ParseQueryString(query));

                    Response.End();
                }

                #endregion
            }

            if (RequestUtil.CompressStaticContent(Context))
            {
                return;
            }

            MaxLabs.WebEngine.Context.Init();

            if (BbsRouter.Route())
            {
                Context.Items.Add("need-compress", true);

                JobManager.ExecuteBeforeRequestJobs();

                MaxLabs.bbsMax.Entities.User user = MaxLabs.bbsMax.Entities.User.Current;

                if (user != null && user.UserID > 0)
                {
                    string ip = IPUtil.GetCurrentIP();

                    if (ip != user.LastVisitIP)
                    {
                        LogManager.LogUserIPChanged(new UserIPLog(user.UserID, user.Username, ip, user.LastVisitIP, Request.RawUrl));

//                        MaxLabs.bbsMax.Logs.LogManager.LogOperation(new Logs.User_IPChange(user.UserID, user.Username, user.LastVisitIP == null ? string.Empty : user.LastVisitIP, ip));

                        UserBO.Instance.UpdateLastVisitIP(user.UserID, ip);
                    }
                }

                Stopwatch processTimer = new Stopwatch();

                processTimer.Start();

                HttpContext.Current.Items["MaxLabs.bbsMax.ProcessTimer"] = processTimer;
            }
            else
            {
                #region 根据路径来决定是否允许请求。例如某些文件夹只允许请求图片而某些文件夹什么都不允许请求

                string path = Request.Url.AbsolutePath.Substring(Globals.AppRoot.Length).Trim('/', '\\');
                string file = Request.Url.LocalPath;

                //max-templates目录、max-spacestyles目录和max-assets目录禁止可执行文件
                if (StringUtil.StartsWithIgnoreCase(path, "max-templates/") || StringUtil.StartsWithIgnoreCase(path, "max-spacestyles/") || StringUtil.StartsWithIgnoreCase(path, "max-assets/"))
                {
                    if (IsExecuteableFile(file))
                    {
                        Response.Redirect("~/");
                        return;
                    }
                }

                //max-temp和UserFiles目录只允许访问图片
                else if (StringUtil.StartsWithIgnoreCase(path, "max-temp/") || StringUtil.StartsWithIgnoreCase(path, "UserFiles/"))
                {
                    if (IsImageFile(file) == false)
                    {
                        Response.Redirect("~/");
                        return;
                    }
                }

                else if (StringUtil.EndsWithIgnoreCase(file, ".aspx"))
                {
                    Context.Items.Add("need-compress", true);
                }

                #endregion
            }
        }
Exemplo n.º 26
0
        public static bool CheckAuth(out int uid)
        {
            RequestUtil req = new RequestUtil();
            string account = req.String("account", false, "授权错误");
            string auth = req.String("auth", false, "授权错误");

            if (req.HasError)
            {
                Json.Write(new { success = false, returnCode = "0000", msg = req.FirstError, errors = req.GetErrors() }, HttpContext.Current.Response.Output);
            }
            else if (CheckAuth(account, auth))
            {
                uid = GetAccountID(account);
                return true;
            }
            else
            {
                Json.Write(new { success = false, returnCode = "0000", msg = "授权错误" }, HttpContext.Current.Response.Output);
            }
            uid = 0;
            return false;
        }
Exemplo n.º 27
0
        public async Task <ActionResult <BindStatusResponse> > CheckUser(LoginPasswordRequest req)
        {
            if (!ModelState.IsValid)
            {
                var error = ModelState.First(m => m.Value.Errors.Count > 0);
                return(new BindStatusResponse
                {
                    Code = Error.Codes.InvalidData.AsString(),
                    Message = Error.Codes.InvalidData.AsMessage(
                        error.Key, error.Value.Errors[0].ErrorMessage),
                });
            }

            try
            {
                string baseurl = req.UniFLOWRestServiceURL;
                string key     = settings["UniflowService:EncryptKey"];
                string salt    = EncryptUtil.CreateCryptographicallySecureGuid();

                string login    = EncryptUtil.Encrypt(req.Login.Trim(), key, salt);
                string password = EncryptUtil.Encrypt(req.Password.Trim(), key, salt);

                string url = $"{baseurl}/WECHAT/CHECKUSER/{login}/{password}";
                _logger.LogTrace("Get " + url);
                var result = await RequestUtil.HttpGetAsync(url);

                _logger.LogTrace("Response: " + result);

                var xdoc    = XElement.Parse(result);
                var ns      = xdoc.GetDefaultNamespace();
                var status  = xdoc.Element(ns.GetName("Status")).Value;
                var bindId  = xdoc.Element(ns.GetName("UserRef")).Value;
                var code    = xdoc.Element(ns.GetName("ErrorCode")).Value;
                var message = status == "0" ? Error.Codes.OK.AsMessage() :
                              code.AsCode().AsMessage(xdoc.Element(ns.GetName("ErrorDesc")).Value);

                var response = new BindStatusResponse
                {
                    Code        = code,
                    Message     = message,
                    BindId      = bindId,
                    LdapLoginId = req.Login,
                };

                if (status != "0")
                {
                    return(response);
                }

                var bind = _ctx.BindUsers.Find(bindId);
                if (bind == null)
                {
                    _ctx.BindUsers.Add(new BindUser
                    {
                        BindUserId = bindId,
                        UserLogin  = req.Login,
                    });
                    await _ctx.SaveChangesAsync();
                }
                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "CheckUser Error");
                return(new BindStatusResponse
                {
                    Code = Error.Codes.Exception.AsString(),
                    Message = Error.Codes.Exception.AsMessage(
                        ex.Message),
                });
            }
        }
Exemplo n.º 28
0
        public async Task <ActionResult <StatusResponse> > ExternalUnlock(ExternalIdUnlockRequest req)
        {
            if (!ModelState.IsValid)
            {
                var error = ModelState.First(m => m.Value.Errors.Count > 0);
                return(new StatusResponse
                {
                    Code = Error.Codes.InvalidData.AsString(),
                    Message = Error.Codes.InvalidData.AsMessage(
                        error.Key, error.Value.Errors[0].ErrorMessage),
                });
            }

            try
            {
                var bind = await _ctx.ExternBindings.FirstAsync(t => t.ExternalId == req.ExternalId && t.Type == req.Type);

                if (bind == null || bind.BindTime == null)
                {
                    return(new StatusResponse
                    {
                        Code = Error.Codes.BindNotFound.AsString(),
                        Message = Error.Codes.BindNotFound.AsMessage(),
                    });
                }

                string baseurl = req.UniFLOWRestServiceURL;
                string key     = settings["UniflowService:EncryptKey"];

                string openid = EncryptUtil.Encrypt(bind.BindUserId, key);
                string serial = req.Serial;

                string url = $"{baseurl}/WECHAT/UNLOCK/{openid}/{serial}";
                _logger.LogTrace("Get " + url);
                var result = await RequestUtil.HttpGetAsync(url);

                _logger.LogTrace("Response: " + result);

                var xdoc    = XElement.Parse(result);
                var ns      = xdoc.GetDefaultNamespace();
                var status  = xdoc.Element(ns.GetName("Status")).Value;
                var code    = xdoc.Element(ns.GetName("ErrorCode")).Value;
                var message = status == "0" ? Error.Codes.OK.AsMessage() :
                              code.AsCode().AsMessage(xdoc.Element(ns.GetName("ErrorDesc")).Value);

                return(new StatusResponse
                {
                    Code = code,
                    Message = message,
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ExternalUnlock Error");
                return(new StatusResponse
                {
                    Code = Error.Codes.Exception.AsString(),
                    Message = Error.Codes.Exception.AsMessage(
                        ex.Message),
                });
            }
        }
Exemplo n.º 29
0
        public async Task <ActionResult <StatusResponse> > Bind(BindExternalIdRequest req)
        {
            if (!ModelState.IsValid)
            {
                var error = ModelState.First(m => m.Value.Errors.Count > 0);
                return(new StatusResponse
                {
                    Code = Error.Codes.InvalidData.AsString(),
                    Message = Error.Codes.InvalidData.AsMessage(
                        error.Key, error.Value.Errors[0].ErrorMessage),
                });
            }

            try
            {
                var bind = await _ctx.BindUsers.FindAsync(req.BindId);

                if (bind == null)
                {
                    var code = Error.Codes.BindNotFound;
                    return(new StatusResponse
                    {
                        Code = code.AsString(),
                        Message = code.AsMessage(),
                    });
                }

                if (!bind.IsBinded)
                {
                    string baseurl = req.UniFLOWRestServiceURL;
                    string key     = settings["UniflowService:EncryptKey"];

                    string openid = EncryptUtil.Encrypt(bind.BindUserId, key);

                    string url = $"{baseurl}/WECHAT/BINDUSER/{req.BindId}/{openid}";
                    _logger.LogTrace("Get " + url);
                    var result = await RequestUtil.HttpGetAsync(url);

                    _logger.LogTrace("Response: " + result);

                    var xdoc    = XElement.Parse(result);
                    var ns      = xdoc.GetDefaultNamespace();
                    var status  = xdoc.Element(ns.GetName("Status")).Value;
                    var code    = xdoc.Element(ns.GetName("ErrorCode")).Value;
                    var message = status == "0" ? Error.Codes.OK.AsMessage() :
                                  code.AsCode().AsMessage(xdoc.Element(ns.GetName("ErrorDesc")).Value);

                    if (status != "0")
                    {
                        return(new StatusResponse
                        {
                            Code = code,
                            Message = message,
                        });
                    }

                    bind.BindTime = DateTime.Now;
                    bind.IsBinded = true;
                    await _ctx.SaveChangesAsync();
                }

                var externBind = _ctx.ExternBindings
                                 .Where(b => b.BindUserId == bind.BindUserId && b.Type == req.Type && b.ExternalId == req.ExternalId)
                                 .FirstOrDefault();

                if (externBind == null)
                {
                    _ctx.ExternBindings.Add(new ExternBinding
                    {
                        BindUserId = bind.BindUserId,
                        Type       = req.Type,
                        ExternalId = req.ExternalId,
                        BindTime   = DateTime.Now,
                    });
                    await _ctx.SaveChangesAsync();
                }

                return(new StatusResponse
                {
                    Code = Error.Codes.OK.AsString(),
                    Message = Error.Codes.OK.AsMessage(),
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Bind Error");
                return(new StatusResponse
                {
                    Code = Error.Codes.Exception.AsString(),
                    Message = Error.Codes.Exception.AsMessage(
                        ex.Message),
                });
            }
        }
Exemplo n.º 30
0
        public void TestGetEndpointURL()
        {
            Minio.RequestUtil.GetEndpointURL("s3.amazonaws.com", true);
            object[] parameterValuesArray =
            {
                new Object[] { "s3.amazonaws.com",            true, "testbucket", null, false },
                new object[] { "testbucket.s3.amazonaws.com", true }
            };
            object[] parameterValuesArray1 =
            {
                "s3.amazonaws.com", true, "testbucket", "testobject", false
            };

            object[][] testCases =
            {
                new Object[]     {
                    new Object[] { "s3.cn-north-1.amazonaws.com.cn",         true  },
                    new Object[] { "https://s3.cn-north-1.amazonaws.com.cn", null, true}
                },
                new Object[]     {
                    new Object[] { "s3.amazonaws.com:443",                   true  },
                    new Object[] { "https://s3.amazonaws.com:443",           null, true}
                },
                new Object[]     {
                    new Object[] { "s3.amazonaws.com",                       true  },
                    new Object[] { "https://s3.amazonaws.com",               null, true}
                },


                new Object[]     {
                    new Object[] { "s3.amazonaws.com",                       false },
                    new Object[] { "http://s3.amazonaws.com",                null, true}
                },

                new Object[]     {
                    new Object[] { "192.168.1.1:9000",                       false },
                    new object[] { "http://192.168.1.1:9000",                null, true}
                },
                new Object[]     {
                    new Object[] { "192.168.1.1:9000",                       true  },
                    new object[] { "https://192.168.1.1:9000",               null, true}
                },
                new Object[]     {
                    new Object[] { "13333.123123.-",                         true  },
                    new object[] { "",                                       new InvalidEndpointException("Endpoint: 13333.123123.- does not follow ip address or domain name standards."), false}
                },

                new Object[]     {
                    new Object[] { "s3.aamzza.-",                            true  },
                    new object[] { "",                                       new InvalidEndpointException("Endpoint: s3.aamzza.- does not follow ip address or domain name standards."), false}
                },
                new Object[]     {
                    new Object[] { "",                                       true  },
                    new object[] { "",                                       new InvalidEndpointException("Endpoint:  does not follow ip address or domain name standards."), false}
                },
            };
            for (int i = 0; i < testCases.Length; i++)
            {
                Object[] testdata       = testCases[i];
                Object[] testCase       = (Object[])testdata[0];
                Object[] expectedValues = (Object[])testdata[1];
                try
                {
                    Uri endPointURL = RequestUtil.GetEndpointURL((string)testCase[0], (bool)testCase[1]);
                    Assert.AreEqual(endPointURL.OriginalString, expectedValues[0]);
                }
                catch (InvalidEndpointException ex)
                {
                    Assert.AreEqual(ex.Message, ((InvalidEndpointException)expectedValues[1]).Message);
                }
            }
        }
Exemplo n.º 31
0
        public ActionResult Upload(string dir = null)
        {
            //定义允许上传的文件扩展名
            Dictionary<string, string> extTable = new Dictionary<string, string>();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
            String dirName = dir;
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                return showError("目录名不正确。");
            }

            RequestUtil req = new RequestUtil();
            var file = req.File("imgFile", false, "请选择文件。", extTable[dirName], "上传文件扩展名是不允许的扩展名。\n只允许" + extTable[dirName] + "格式。");

            if (req.HasError)
            {
                return showError(req.FirstError);
            }

            String src = file.Save();
            String fileUrl = RequestFile.FullUrl(src);

            return Content(System.Web.Helpers.Json.Encode(new { error = 0, url = fileUrl, src = src }));
        }
Exemplo n.º 32
0
 /// <summary>
 /// Creates a REST API request (with appropriate authentication headers).
 /// </summary>
 /// <param name="rel">This parameter is currently unused.</param>
 /// <returns>
 /// A REST API requeset (with appropriate authentication headers).
 /// </returns>
 protected override IRestRequest CreateRequestForEmbeddedResource(String rel)
 {
     return(RequestUtil.ApplyFamilySearchConneg(CreateAuthenticatedRequest()));
 }
Exemplo n.º 33
0
        public ActionResult GetClientIP()
        {
            string clientIp = $"REMOTE_ADDR:{Request.ServerVariables["REMOTE_ADDR"]},HTTP_X_REAL_IP:{Request.ServerVariables["HTTP_X_REAL_IP"]},HTTP_X_FORWARDED_FOR:{Request.ServerVariables["HTTP_X_FORWARDED_FOR"]},HTTP_CLIENT_IP:{Request.ServerVariables["HTTP_CLIENT_IP"]},GetClientIP:{RequestUtil.GetClientIP()}";

            return(OK(clientIp));
        }
Exemplo n.º 34
0
        public ActionResult ImagePreview()
        {
            RequestUtil req = new RequestUtil();

            string callback = req.String("callback");
            int width = req.Int("width", defaultValue: 640);
            int height = req.Int("height", defaultValue: 1024);

            HttpPostedFileBase pic = Request.Files.Count == 0 ? null : Request.Files[0];
            if (pic != null && pic.ContentLength != 0)
            {
                byte[] imageBuffer = ImageUtil.Compress(pic.InputStream, 40, width, height);

                string guid = System.Guid.NewGuid().ToString("N");

                CacheUtil.CreateCache("preview-" + guid, 0.1, imageBuffer);

                return Content(HtmlUtil.Result(callback, new { success = true, guid = guid, name = Request.Files.Keys[0] }));
            }
            else
            {
                return Content(HtmlUtil.Result(callback, new { success = false, msg = "您还未选择图片" }));
            }
        }