public void OnAuthorization(AuthorizationContext filterContext) { if (!Client.IsLogin) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { ContentResult cr = new ContentResult(); cr.Content = "{msg:'forbidden',isLogin:'******'}"; filterContext.Result = cr; } else { filterContext.HttpContext.Response.Redirect(C.APP); } } if (requireAdmin && Client.IsLogin) { if (!Client.IsAdministrator) { ContentResult cr = new ContentResult(); cr.Content = "{msg:'forbidden to access',isLogin:'******',isAdmin:'false'}"; filterContext.Result = cr; } } }
public ActionResult GetAnswer(string researchIdName,int skip) { var content = new ContentResult() { ContentEncoding = System.Text.Encoding.UTF8 }; content.Content = GoocaBoocaDataModels.Utility.CrossTableConvert.CreateAnswerData(researchIdName,skip); return content; }
/// <summary> /// Called before an action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { // Continue normally if the model is valid. if (filterContext == null || filterContext.Controller.ViewData.ModelState.IsValid) { return; } var serializationSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; // Serialize Model State for passing back to AJAX call var serializedModelState = JsonConvert.SerializeObject( filterContext.Controller.ViewData.ModelState, serializationSettings); var result = new ContentResult { Content = serializedModelState, ContentType = "application/json" }; filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; filterContext.Result = result; }
public virtual JsonResult ImagenSizeValidation(HttpPostedFileBase fileToUpload) { try { Session["ImagenFile"] = null; var result = new ContentResult(); string resp = "No Eligio ningun Archivo"; //Parametro parametro = new Parametro(); var parametro = 100000; // ParametroNegocio.GetParameById("MaxImageSizeUpload", marketid); int imagesize = 1024; int size = int.MinValue; if (parametro != null && !string.IsNullOrEmpty(parametro.ToString())) { bool esnum = Int32.TryParse(parametro.ToString(), out size); if (esnum) imagesize = size; } if (fileToUpload != null) { if (!fileToUpload.ContentType.Contains("image")) { resp = "Tipo de archivo no valido!"; return new JsonResult { Data = resp, ContentType = "text/html" }; } if (fileToUpload.ContentLength > (imagesize * 1000)) { resp = LenceriaKissy.Recursos.AppResources.Vistas.MaxImageSize + " " + parametro + " KB."; } else { int nFileLen = fileToUpload.ContentLength; byte[] resultado = new byte[nFileLen]; fileToUpload.InputStream.Read(resultado, 0, nFileLen); //Session.Add("ImagenFile", resultado); Session["ExtensionImagen"] = fileToUpload.ContentType.Split('/')[1]; resp = LenceriaKissy.Recursos.AppResources.Vistas.OK; } } if (resp == LenceriaKissy.Recursos.AppResources.Vistas.OK) { string newFileName = Guid.NewGuid().ToString().Trim().Replace("-", "") + System.IO.Path.GetExtension(fileToUpload.FileName); var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(newFileName)); fileToUpload.SaveAs(fileName); Session["ImagenFile"] = "/uploads/" + System.IO.Path.GetFileName(newFileName); } return new JsonResult { Data = resp, ContentType = "text/html", JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } catch (Exception ex) { return new JsonResult { Data = ex.Message, ContentType = "text/html", JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
public ContentResult GetTree() { ContentResult contentResult = new ContentResult(); string strSql = Request.QueryString["sql"]; if (strSql.Trim().Contains(" ")) { throw new Exception("参数“sql”格式错误!"); } var dtTree = _dba.QueryDataTable(strSql); List<TreeModel> lsTree = new List<TreeModel>(); foreach (DataRow row in dtTree.Rows) { lsTree.Add(new TreeModel() { id = row["id"].ToString(), parentId = row["parentId"].ToString(), text = row["text"].ToString(), state = TreeModel.State.open.ToString() }); } contentResult.Content = Newtonsoft.Json.JsonConvert.SerializeObject(TreeModel.ToTreeModel(lsTree)); return contentResult; }
public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.Controller.ViewData.ModelState.IsValid) { if (filterContext.HttpContext.Request.HttpMethod == "GET") { var result = new HttpStatusCodeResult(HttpStatusCode.BadRequest); filterContext.Result = result; } else { var result = new ContentResult(); string content = JsonConvert.SerializeObject(filterContext.Controller.ViewData.ModelState, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); result.Content = content; result.ContentType = "application/json"; filterContext.HttpContext.Response.StatusCode = 400; filterContext.Result = result; } } }
public ContentResult Create(string json) { OdbcConnection hiveConnection = new OdbcConnection("DSN=Hadoop Server;UID=hadoop;PWD=hadoop"); hiveConnection.Open(); Stream req = Request.InputStream; req.Seek(0, SeekOrigin.Begin); string request = new StreamReader(req).ReadToEnd(); ContentResult response; string query; try { query = "INSERT INTO TABLE error_log (json_error_log) VALUES('" + request + "')"; OdbcCommand command = new OdbcCommand(query, hiveConnection); command.ExecuteNonQuery(); command.CommandText = query; response = new ContentResult { Content = "{status: 1}", ContentType = "application/json" }; hiveConnection.Close(); return response; } catch(WebException error) { response = new ContentResult { Content = "{status: 0, message:" + error.Message.ToString()+ "}" }; System.Diagnostics.Debug.WriteLine(error.ToString()); hiveConnection.Close(); return response; } }
public ActionResult Process(HttpRequestBase request, ModelStateDictionary modelState) { PdtVerificationBinder binder = new PdtVerificationBinder(); Transaction tx = binder.Bind(request.Form, modelState); ContentResult cr = new ContentResult(); cr.ContentEncoding = Encoding.UTF8; cr.ContentType = "text/html"; cr.Content = "FAIL\n"; if (tx != null) { Transaction dbTx = m_txRepository.GetAll().Where(x => x.Tx == tx.Tx).FirstOrDefault(); if (dbTx != null && dbTx.AuthToken == tx.AuthToken) { StringBuilder sb = new StringBuilder(); sb.Append("SUCCESS\n"); sb.Append(BuildContent(dbTx)); cr.Content = sb.ToString(); } } return cr; }
public ActionResult StartDatabaseBackup() { try { var dc = new ProcurementDataClassesDataContext(ConfigurationManager.ConnectionStrings["BidsForKidsConnectionString"].ConnectionString); var result = new ContentResult(); var backupLocation = ConfigurationManager.AppSettings["SQLBackupLocation"]; if (string.IsNullOrEmpty(backupLocation) == true) { throw new ApplicationException("SQLBackupLocation is not set in web.config"); } dc.BackupDatabase(backupLocation); result.Content = "Database has been backed up."; return result; } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return new ContentResult { Content = "Error backing up database: " + ex.Message }; } }
public ActionResult GenerateDonorReport(DonorReportSetupVideModel reportSetup) { var donors = reportSetup.AuctionYearFilter == 0 ? Mapper.Map<IEnumerable<Donor>, IEnumerable<DonorReportViewModel>>(repo.GetDonors()).ToList() : Mapper.Map<IEnumerable<Donor>, IEnumerable<DonorReportViewModel>>(repo.GetDonors(reportSetup.AuctionYearFilter)).ToList(); donors = ApplyDonorFilters(donors, reportSetup); if (reportSetup.BusinessType == false) donors.Where(x => x.DonorType == "Business").ToList().ForEach(x => donors.Remove(x)); if (reportSetup.ParentType == false) donors.Where(x => x.DonorType == "Parent").ToList().ForEach(x => donors.Remove(x)); var reportHtml = new StringBuilder(); reportHtml.AppendLine("<h3>" + reportSetup.ReportTitle + "</h3>"); reportHtml.AppendLine("<table class=\"customReport\">"); reportHtml.AppendLine("<tbody>"); var selectedColumns = GetSelectedColumns(reportSetup); BuildHeaders(selectedColumns, reportHtml, reportSetup.IncludeRowNumbers); BuildReportBody(selectedColumns, donors, reportHtml, reportSetup.IncludeRowNumbers); reportHtml.AppendLine("</tbody>"); reportHtml.AppendLine("</table>"); var result = new ContentResult() { Content = reportHtml.ToString() }; return result; }
public ActionResult Projekte () { ContentResult Result = new ContentResult(); Result.Content = MapWrapper.MapDataWrapper.Instance.CreateOSMPhasenOrientedLocations (WordUp23.Basics.ShowDatenTyp.Projekt); return Result; }
public ContentResult Edit(string id, string value) { var a = id.Split('.'); var c = new ContentResult(); c.Content = value; var p = DbUtil.Db.Programs.SingleOrDefault(m => m.Id == a[1].ToInt()); if (p == null) return c; switch (a[0]) { case "ProgramName": p.Name = value; break; case "RptGroup": p.RptGroup = value; break; case "StartHours": p.StartHoursOffset = value.ToDecimal(); break; case "EndHours": p.EndHoursOffset = value.ToDecimal(); break; } DbUtil.Db.SubmitChanges(); return c; }
public ActionResult Process(HttpRequestBase request, ModelStateDictionary modelState) { IpnVerificationBinder binder = new IpnVerificationBinder(); Transaction tx = binder.Bind(request.Form, modelState); ContentResult cr = new ContentResult(); cr.ContentEncoding = Encoding.UTF8; cr.ContentType = "text/html"; cr.Content = "INVALID"; if (tx != null) { Transaction dbTx = m_txRepository.GetAll().Where(x => x.Tx == tx.Tx).FirstOrDefault(); if (dbTx != null) { string expected = dbTx.ToIpnQueryString().ToString(); QueryString actualQs = new QueryString(); actualQs.Add(request.Form); actualQs.Remove("cmd"); string actual = actualQs.ToString(); if (expected == actual) { cr.Content = "VERIFIED"; } } } return cr; }
// GET: Employee public ActionResult GetEmployees() { List<EmployeeVM> list = new List<EmployeeVM>() { new EmployeeVM() { FullName = "Alper Dortbudak" }, new EmployeeVM() { FullName = "Connor Dortbudak" } }; var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); var jsonResult = new ContentResult { Content = JsonConvert.SerializeObject(list, camelCaseFormatter), ContentType = "application/json" }; return jsonResult; }
/// <summary> /// Relays an HttpWebResponse as verbatim as possible. /// </summary> /// <param name="responseToRelay">The HTTP response to relay.</param> public HttpWebResponseResult(HttpWebResponse responseToRelay) { if (responseToRelay == null) { throw new ArgumentNullException("response"); } _response = responseToRelay; Stream contentStream; if (responseToRelay.ContentEncoding.Contains("gzip")) { contentStream = new GZipStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress); } else if (responseToRelay.ContentEncoding.Contains("deflate")) { contentStream = new DeflateStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress); } else { contentStream = responseToRelay.GetResponseStream(); } if (string.IsNullOrEmpty(responseToRelay.CharacterSet)) { // File result _innerResult = new FileStreamResult(contentStream, responseToRelay.ContentType); } else { // Text result var contentResult = new ContentResult(); contentResult = new ContentResult(); contentResult.Content = new StreamReader(contentStream).ReadToEnd(); _innerResult = contentResult; } }
public ActionResult DeleteBlobs() { IContentRepository repo = ServiceLocator.Current.GetInstance<IContentRepository>(); BlobFactory blobFactory = ServiceLocator.Current.GetInstance<BlobFactory>(); var assetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>(); StringBuilder sb = new StringBuilder(); IEnumerable<ContentReference> contentReferences = null; contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.GlobalBlockFolder); DeleteBlobs(contentReferences, repo, sb, blobFactory); DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory); contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.SiteBlockFolder); DeleteBlobs(contentReferences, repo, sb, blobFactory); DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory); // Private page folders too contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.StartPage); DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory); ContentResult result = new ContentResult(); result.Content = sb.ToString(); return result; }
public ActionResult Play() { ViewData["PageTitle"] = "人人翁 主游戏"; RecordFromPage rfp = new RecordFromPage(); int pageindex = 1; int type = 1; rfp.ConnStr = DBHelper.ConnStr; rfp.TableName = "T_Game"; rfp.PageIndex = pageindex; rfp.Where = " F_Type=" + type.ToString(); rfp.Fields = "*"; rfp.OrderFields = "F_Phases desc"; rfp.PageSize = 20; DataTable dt=rfp.GetDt(); if (dt == null || dt.Rows.Count == 0) { ContentResult cr = new ContentResult(); cr.ContentType = "text/html"; cr.Content = "Table NULL"; return cr; } if(pageindex==1) { for(int i=0;i<3;i++) { DataRow dr= dt.NewRow(); dr["F_Phases"]=Convert.ToInt32(dt.Rows[0]["F_Phases"])+1; dr["F_LotteryDate"]=Convert.ToDateTime(dt.Rows[0]["F_LotteryDate"]).AddMinutes(3); dr["F_NumOne"]=0; dr["F_NumTwo"]=0; dr["F_NumThree"]=0; dr["F_Bonus"]=0; dr["F_Id"]=0; dr["F_InvolvedNum"]=0; dr["F_WinningNum"]=0; dr["F_Lottery"]=false; dt.Rows.InsertAt(dr,0); } } string defimgattr = " border='0' align='absmiddle' width='18' height='21' style='display:inline'"; switch (type) { case 1: ViewData["LotteryShow"] = "<img " + defimgattr + " src='../Content/numimg/0{0}.jpg'> + <img " + defimgattr + " src='../Content/numimg/0{1}.jpg'>+<img " + defimgattr + " src='../Content/numimg/0{2}.jpg'>=<img " + defimgattr + " src='../Content/numimg/{3}.jpg'>"; break; case 2: ViewData["LotteryShow"] = " {0}X{1}X{2}X{3}"; break; default: ViewData["LotteryShow"] = "{0}-{1}-{2}-{3}"; break; } ViewData["GameType"] = type.ToString(); ViewData["ConentTable"] = dt; return View(); }
public ContentResult Edit(string id, string value) { var a = id.Split('.'); var c = new ContentResult(); c.Content = value; if (a[1] == value) return c; var existingrole = DbUtil.Db.Roles.SingleOrDefault(m => m.RoleName == value); var role = DbUtil.Db.Roles.SingleOrDefault(m => m.RoleName == a[1]); if (role == null) { TempData["error"] = "no role"; return Content("/Error/"); } if (existingrole != null && existingrole.RoleName != role.RoleName) { TempData["error"] = "duplicate role"; return Content("/Error/"); } switch (a[0]) { case "RoleName": role.RoleName = value; break; } DbUtil.Db.SubmitChanges(); return c; }
public ActionResult GameTimer() { ContentResult cres = new ContentResult(); cres.ContentType = "text/html"; string cont = null; string game = Request.Form["gtype"].ToString(); switch (Convert.ToInt32(game)) { case 1: cont = "GameOneTimer"; break; case 2: cont = "GameTwoTimer"; break; default: cont = "ERROR"; break; } HttpContext.Application.Lock(); if (HttpContext.Application[cont] != null) { cont = HttpContext.Application[cont].ToString(); } HttpContext.Application.UnLock(); Manage_T_Game mtg = new Manage_T_Game(); int pid = mtg.GetNewPhases(Convert.ToInt32(game)); cres.Content ="{\"id\":\""+pid.ToString()+"\",\"timer\":\""+cont+"\"}"; return cres; }
/// <summary> /// /// </summary> /// <param name="costCentreApplicationId"></param> /// <param name="lastDeliveredCommandRouteItemId">-1 if never requested before</param> /// <returns></returns> public ActionResult GetNextDocumentCommand(Guid costCentreApplicationId, long lastDeliveredCommandRouteItemId) { _log.InfoFormat("GetNextDocumentCommand from CCAPPId : {0} with lastDeliveredCommandRouteItemId : {1}", costCentreApplicationId, lastDeliveredCommandRouteItemId); Guid ccid = _costCentreApplicationService.GetCostCentreFromCostCentreApplicationId(costCentreApplicationId); DocumentCommandRoutingResponse response = null; try { if (_costCentreApplicationService.IsCostCentreActive(costCentreApplicationId)) response = _commandRouterResponseBuilder.GetNextDocumentCommand(costCentreApplicationId, ccid, lastDeliveredCommandRouteItemId); else response = new DocumentCommandRoutingResponse { ErrorInfo = "Inactive CostCentre Application Id" }; } catch (Exception ex ) { response = new DocumentCommandRoutingResponse { ErrorInfo = "Failed to get next document command" }; _log.InfoFormat("ERROR GetNextDocumentCommand from CCAPPId : {0} with lastDeliveredCommandRouteItemId : {1}", costCentreApplicationId, lastDeliveredCommandRouteItemId); _log.Error(ex); } ContentResult result = new ContentResult { Content = JsonConvert.SerializeObject(response), ContentType = "application/json", ContentEncoding = Encoding.UTF8 }; AuditCCHit(ccid, "GetNextDocumentCommand", result.Content, "OK" ); return result; }
public ActionResult Index() { ContentResult cr = new ContentResult(); cr.ContentType = "text/html"; cr.Content = "HTML FILE NULL"; return cr; }
/// <summary> /// Converts a command result to an action result. /// </summary> /// <param name="commandResult">The source command result.</param> /// <returns>Action result</returns> /// <remarks>The reason to use a separate command result at all, instead /// of simply using ActionResult is that the core library should not /// be Mvc dependant.</remarks> public static ActionResult ToActionResult(this CommandResult commandResult) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } switch (commandResult.HttpStatusCode) { case HttpStatusCode.SeeOther: return new RedirectResult(commandResult.Location.OriginalString); case HttpStatusCode.OK: var result = new ContentResult() { Content = commandResult.Content }; if(!string.IsNullOrEmpty(commandResult.ContentType)) { result.ContentType = commandResult.ContentType; } return result; default: throw new NotImplementedException(); } }
// // GET: /Images/ public ActionResult Index () { //ContentResult contentResult1 = new ContentResult(); //contentResult1.Content = "Fehler - " + System.Web.HttpContext.Current.Application.Identity; //return contentResult1; ImageFolder viewFolder = new ImageFolder (); string msg = ""; FolderInfo folderInfo = new FolderInfo (); if (Configurations.ViewFolders.Count == 0) { msg = Configurations.Reload (); } if (Configurations.ViewFolders.Count != 0) { folderInfo.Folder = new DirectoryInfo (Configurations.ViewFolders [0].LocalFolderPath); folderInfo.WebUri = new Uri (Configurations.ViewFolders [0].WebFolderPath); folderInfo.ThumbsFolder = "Thumbs/"; viewFolder.AnalyzeFolder (folderInfo); return View ("FolderView", viewFolder); } ContentResult contentResult = new ContentResult (); contentResult.Content = "Fehler - " + msg; return contentResult; }
public ActionResult Proxy(string url) { var uri = new Uri(url, UriKind.RelativeOrAbsolute); var request = WebRequest.Create(uri); var task = Task.Factory.StartNew<string>(() => { using (var stream = request.GetResponse().GetResponseStream()) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } }); task.Wait(); var originalHtml = task.Result; var hrefPattern = "(?<=href=\")(?<url>.*?)(?=\")"; //var replacement = "/proxy?url=${url}"; var processedHtml = Regex.Replace(originalHtml, hrefPattern, new MatchEvaluator(UrlEscaper)); var result = new ContentResult(); result.Content = processedHtml; return result; }
public ActionResult ReloadConfig () { ContentResult result = new ContentResult (); result.Content = Configurations.Reload (); return result; }
/// <summary>权限认证</summary> /// <param name="filterContext"></param> public override void OnAuthorization(AuthorizationContext filterContext) { //登录权限认证 if (!ManageProvider.Provider.IsOverdue()) { filterContext.Result = new RedirectResult("~/Login/Default"); } //防止被搜索引擎爬虫、网页采集器 if (!this.PreventCreeper()) { filterContext.Result = new RedirectResult("~/Login/Default"); } //权限拦截是否忽略 if (_CustomMode == PermissionMode.Ignore) { return; } //执行权限认证 if (!this.ActionAuthorize(filterContext)) { ContentResult Content = new ContentResult(); Content.Content = "<script type='text/javascript'>top.Loading(false);alert('很抱歉!您的权限不足,访问被拒绝!');</script>"; filterContext.Result = Content; } }
public ActionResult GetQuestion(string researchIdName) { var content = new ContentResult() { ContentEncoding = System.Text.Encoding.UTF8 }; content.Content = GoocaBoocaDataModels.Utility.CrossTableConvert.CreateQuestionData(researchIdName); return content; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (string.IsNullOrEmpty(_ignoreParameter) || string.IsNullOrEmpty(filterContext.RequestContext.HttpContext.Request.QueryString[_ignoreParameter])) { if (!BrowserUtility.BrowserUtility.SideInWeixinBrowser(filterContext.HttpContext)) { //TODO:判断网页版登陆状态 ActionResult actionResult = null; if (!string.IsNullOrEmpty(RedirectUrl)) { actionResult = new RedirectResult(RedirectUrl); } else { actionResult = new ContentResult() { Content = _message }; } filterContext.Result = actionResult; } } base.OnActionExecuting(filterContext); }
public ContentResult HelloWorld() { ContentResult contentResult = new ContentResult(); contentResult.Content = _helloWorldService.SayHello(DateTime.Now.ToString()); return contentResult; }
public ActionResult GetAppStatus() { ContentResult cr = new ContentResult(); IList<ApplicationData> result = mFactory.Management.ListApp(); cr.Content = Newtonsoft.Json.JsonConvert.SerializeObject(result); return cr; }