/// <summary> /// Makes a <c>Formatter</c> object for the given name. /// </summary> /// <param name="formatterName">The name of the <c>Formatter</c> to create.</param> /// <param name="request">The <c>MvcRequest</c> that is used.</param> /// <returns>A <c>Formatter</c> of the specified name.</returns> public static Formatter Make( string formatterName, MvcRequest request) { Formatter formatter = null; string fullName = ""; try { // get the namespace and assembly the actions are in NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection(TritonConfigurationSection.SectionName + "/" + SECTION_NAME); string assemblyName = config["assembly"]; string nameSpace = config["namespace"]; // build the name of the Action object for the given request fullName = string.Format("{0}.{1},{2}", nameSpace, formatterName, assemblyName); formatter = (Formatter) Activator.CreateInstance(Type.GetType(fullName)); formatter.Request = request; } catch (Exception e) { LogManager.GetCurrentClassLogger().Error( errorMessage => errorMessage("FormatterFactory.Make: formatter = {0} : {1} ", fullName, e)); } return formatter; }
public static void Fill(this PersistedAddressFilter filter, MvcRequest request) { if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.ID])) { filter.Ids = request[ParameterNames.PersistedAddress.Filter.ID].ToLongArray(); } if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.LINE1])) { filter.Line1 = request[ParameterNames.PersistedAddress.Filter.LINE1]; } if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.CITY])) { filter.City = request[ParameterNames.PersistedAddress.Filter.CITY]; } if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.STATE])) { filter.State = request[ParameterNames.PersistedAddress.Filter.STATE]; } if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.COUNTRY])) { filter.Country = request[ParameterNames.PersistedAddress.Filter.COUNTRY]; } if (!string.IsNullOrEmpty(request[ParameterNames.PersistedAddress.Filter.POSTALCODE])) { filter.PostalCode = request[ParameterNames.PersistedAddress.Filter.POSTALCODE]; } ((BaseFilter)filter).Fill(request); }
/// <summary> /// Evaluates the rule for the given request. The <b>RegexRule</b> applies its /// regular expression pattern to its specified field in the given request. /// </summary> /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param> /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the /// rule and any validation errors that occurred.</returns> public override ValidationResult Evaluate( MvcRequest request) { ValidationResult result = new ValidationResult { Passed = false }; string fieldVal = request[Field.EvaluatePropertyValue()]; // TODO: what if fieldVal is null?? is it valid or not?? // if the field value is null and the check is not explicitly for null, // add the error if (fieldVal == null) { if (this.Pattern == NULL_PATTERN) { result.Passed = true; } else { result.AddError(Field, ErrorId); } } else { bool passed = Regex.IsMatch(fieldVal, this.Pattern); if (passed) { result.Passed = true; } else { result.AddError(Field, ErrorId); } } return result; }
protected override void OnExecute( MvcRequest request) { // PageTransitionManager ptm = PageTransitionManager.GetInstance(); // // PageState pg = ptm.GetStateByTargetPage(context.Request["p"], this.Section, this.Site); }
public override string Execute( TransitionContext context) { string retEvent = EVENT_ERROR; try { request = context.Request; //idk how we got here and no files are in the request, and technically not an error IList<Model.Media> media = new List<Model.Media>(); string[] files = request[MediaRequestName].Split(','); foreach (string file in files) { media.Add(ProcessFile(file)); } request.Items["size"] = "Successfully uploaded: "; foreach (Model.Media m in media) { request.Items["size"] += string.Format("{0}, ", m.Name); } request.Items[this.RequestItemName] = media; request.Items["result"] = "success"; retEvent = EVENT_OK; } catch (Exception ex) { LogManager.GetLogger(typeof(UploadMediaAction)).Error( errorMessage => errorMessage("Error occured in UploadMediaAction.", ex)); context.Request.Items["result"] = "error"; context.Request.Items["error"] = "Internal error occured when uploading this file."; } return retEvent; }
/// <summary> /// Creates a new <c>AttributeType</c> from the request. /// </summary> /// <param name="request">Request to create the AttributeType from.</param> /// <returns>A populated AttributeType object.</returns> public static AttributeType CreateAttributeType(MvcRequest request) { return Populate(request, new AttributeType() { Id = 0 }); }
/// <summary> /// Creates a new <c>Role</c> from the request. /// </summary> /// <param name="request">Request to create the Role from.</param> /// <returns>A populated Role object.</returns> public static Role CreateRole(MvcRequest request) { return Populate(request, new Role() { Id = 0 }); }
public static MockWebContext New(int userId, String httpMethod, String url, StringWriter sw) { // 构造request/response/httpContext MvcRequest req = new MvcRequest(url); req.HttpMethod = strUtil.IsNullOrEmpty(httpMethod) ? "GET" : httpMethod; MvcResponse res = new MvcResponse(); res.Writer = sw; MvcHttpContext ctx = new MvcHttpContext(); ctx.Request = req; ctx.Response = res; // 同时构造静态context CurrentRequest.setRequest(req); MockWebContext mctx = new MockWebContext(ctx); mctx.setUserId(userId); return(mctx); }
/// <summary> /// Evaluates the rule for the given request. <b>Validator</b> "ands" all of its /// child rules to determine if final result. /// </summary> /// <remarks> /// This override locks the validator before calling the base.Evaluate to ensure /// thread safety. /// </remarks> /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param> /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the /// rule and any validation errors that occurred.</returns> public override ValidationResult Evaluate( MvcRequest request) { lock (this) { return base.Evaluate(request); } }
/// <summary> /// Constructs a <b>PublishException</b> for the given MvcRequest /// and PublishRecord, with the specified message. /// </summary> /// <param name="request">The <b>MvcRequest</b> in which the exception occurred.</param> /// <param name="publishRecord">The <b>PublishRecord</b> in use at the time /// the exception occurred.</param> /// <param name="message">The error message to return.</param> public PublishException( MvcRequest request, PublishRecord publishRecord, string message) : base(message) { this.request = request; this.publishRecord = publishRecord; }
/// <summary> /// Makes a Command object based on the given set of parameters. /// </summary> /// <remarks> /// This methods creates a new command object based on the requested /// <i>action</i> and <i>thing</i> (or type), the target of the action. /// The action is specified by the <b>a</b> parameter and the thing by /// the <b>t</b> parameter.<br> /// For example, the parameters <c>a=get</c> and <c>t=customer</c> will /// cause the creation of a GetCustomerCommand <c>Command</c>. /// </remarks> /// <param name="request">The parameter collection containing the "a" and /// "t" parameters used to create the appropriate <c>Command</c> object.</param> /// <returns>A <c>Command</c> for performing the requested action, or /// <c>UnknownCommand</c> if the requested command does not exist.</returns> public static Command Make( MvcRequest request) { // get the action being requested String action = request[ACTION_PARAM]; // get the thing the action is to be performed on String thing = request[THING_PARAM]; return Make(action, thing); }
public static Account CreateAccount(MvcRequest request) { Account account = new Account { Id = Guid.Empty, CreateDate = DateTime.Now, Person = new Person(), Attributes = new Dictionary<AttributeType, string>(), Usernames = new List<Username>() }; return account; }
/// <summary> /// Populates the <c>Media</c> with the values from the request. /// </summary> /// <param name="request">Request to populate the Media from.</param> /// <param name="media">Media to populate</param> /// <returns>Populated from the request Media object.</returns> public static Model.Media Populate(MvcRequest request, Model.Media media) { if (request[ParameterNames.Media.Field.NAME] != null) { media.Name = request[ParameterNames.Media.Field.NAME]; } if (request[ParameterNames.Media.Field.CREATED_DATE] != null) { DateTime createdDate; if (DateTime.TryParse(request[ParameterNames.Media.Field.CREATED_DATE], out createdDate)) { media.CreatedDate = createdDate; } } if (request[ParameterNames.Media.Field.UPDATED_DATE] != null) { DateTime updatedDate; if (DateTime.TryParse(request[ParameterNames.Media.Field.UPDATED_DATE], out updatedDate)) { media.UpdatedDate = updatedDate; } } if (request[ParameterNames.Media.Field.COMMENTS] != null) { media.Comments = request[ParameterNames.Media.Field.COMMENTS]; } if (request[ParameterNames.Media.Field.SORT_ORDER] != null) { float sortOrder; media.SortOrder = float.TryParse(request[ParameterNames.Media.Field.SORT_ORDER], out sortOrder) ? sortOrder : 0; } if (request[ParameterNames.Media.Field.FILE_NAME] != null && request[ParameterNames.Media.Field.FILE_PATH] != null) { string fileName = request[ParameterNames.Media.Field.FILE_NAME]; string webPath = request[ParameterNames.Media.Field.FILE_PATH]; //string filePath = Path.Combine(WebInfo.BasePath, webPath); media.File = new FileRecord { Name = fileName, Path = webPath }; IMediaTypeDao dao = DaoFactory.GetDao<IMediaTypeDao>(); IList<MediaType> types = dao.Get(new MediaType { FileTypes = new List<string> { GetFileType(fileName) } }); media.Type = types.Count > 0 ? types[0] : dao.Get("misc_docs"); } return media; }
/// <summary> /// /// </summary> /// <param name="filter"></param> /// <param name="request"></param> public static void Fill(this MediaFilter filter, MvcRequest request) { if (!string.IsNullOrEmpty(request["filter_media_id"])) { filter.Ids = request["filter_media_id"].ToIntArray(); } if (!string.IsNullOrEmpty(request["filter_media_name"]) ){ filter.Name = request["filter_media_name"]; } ((BaseFilter)filter).Fill(request); }
/// <summary> /// Constructs a <c>TransitionContext</c> for the given starting state and /// site. /// </summary> /// <param name="startState">The starting state of the context.</param> /// <param name="startEvent">The start event of the context.</param> /// <param name="site">The site of the context.</param> /// <param name="request">The <c>MvcRequest</c>.</param> public TransitionContext( IState startState, string startEvent, string site, MvcRequest request) { this.startState = startState; this.currentState = startState; this.site = site; this.startEvent = startEvent; this.request = request; this.version = SitesConfig.GetInstance().GetSiteVersion(this.site); }
/// <summary> /// Processes a request. /// </summary> /// <param name="request">The <c>MvcRequest</c> object representing the /// request to process.</param> public void ProcessRequest( MvcRequest request) { // if the request has the state (st) and event (e) parameters, // assume we are performing a state transition Command.Command cmd = request[EVENT_PARAM] != null ? CommandFactory.Make(TRANSITION_COMMAND) : CommandFactory.Make(request); if (cmd == null) { LogManager.GetCurrentClassLogger().Error( errorMessage => errorMessage("FrontController.ProcessRequest: could not make Command.")); } else { cmd.Execute(request); } }
public static void setRequest(MvcRequest req) { if (req == null) { setItem("_RawUrl", null); setItem("_UserLanguages", null); setItem("_HttpMethod", null); setItem("_Form", null); } else { setItem("_RawUrl", req.RawUrl); setItem("_UserLanguages", req.UserLanguages); setItem("_HttpMethod", req.HttpMethod); setItem("_Form", req.Form); } }
/// <summary> /// Evaluates the rule for the given request. The <b>RegexRule</b> applies its /// regular expression pattern to its specified field in the given request. /// </summary> /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param> /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the /// rule and any validation errors that occurred.</returns> public override ValidationResult Evaluate( MvcRequest request) { ValidationResult result = new ValidationResult { Passed = true }; if (request.Files.Count == 0 || request.Files[Field] == null) { result.Passed = false; //result.AddError(Field, ErrorId); } else { // get the uploaded file reference MvcPostedFile theFile = request.Files[Field]; if (this.FileType != null) { result.Passed = false; // get the list of acceptable types string[] types = this.FileType.Split(','); // get the extension of the file string ext = this.GetExtension(theFile.Name).ToLower(); // see if the file extension is in the acceptable list foreach (string t in types) { if (ext == t.ToLower()) { result.Passed = true; break; } } } // if a file size limit is specified, check the size // TODO: should we check result.Passed and not do this if we've already failed?? if (this.fileSize.HasValue) { if (theFile.Length > this.fileSize) { result.Passed = false; } } } // if the type check failed and an error ID was specified, add the error if (!result.Passed && (ErrorId > 0)) { result.AddError(Field, ErrorId); } return result; }
/// <summary> /// 异步写入请求信息 /// </summary> /// <param name="model"><see cref="MvcRequest"/> 对象</param> /// <param name="context"><see cref="HttpContext"/> 对象</param> private static void BeginLogMvcRequest(MvcRequest model, HttpContext context) { var _path = $"{_Map}request.txt"; var _fileInfo = new FileInfo(_path); var _dir = _fileInfo.Directory; if (!_dir.Exists) { _dir.Create(); //如果文件夹不存在,则创建 } //允许多个线程同时写入 using (var fileStream = new FileStream(_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { var streamWrite = new StreamWriter(fileStream, Encoding.Default); try { streamWrite.BaseStream.Seek(0, SeekOrigin.End); streamWrite.WriteLine(DateTime.Now.ToFormatDateTime()); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n 请求信息:"); streamWrite.WriteLine($"\r\n\t浏览器标识:{model.UserAgent}"); streamWrite.WriteLine($"\r\n\t请求地址:{model.Url}"); streamWrite.WriteLine($"\r\n\t请求参数:{model.Params}"); streamWrite.WriteLine($"\r\n\t请求类型:{model.RequestType}"); streamWrite.WriteLine($"\r\n\t控制器名:{model.ControllerName}"); streamWrite.WriteLine($"\r\n\tAction名:{model.ActionName}"); streamWrite.WriteLine($"\r\n\tIp 地址:{model.IpAddress}"); streamWrite.WriteLine($"\r\n\t线程 ID:{model.ThreadId}"); streamWrite.WriteLine($"\r\n\t消耗时间:{model.ConsumingTime} s"); //日志分隔线 streamWrite.WriteLine("--------------------------------------------------------------------------------------------------------------\n"); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n"); } finally { streamWrite.Flush(); streamWrite.Close(); } } }
/// <summary> /// 异步写入请求信息 /// </summary> /// <param name="model"><see cref="MvcRequest"/> 对象</param> /// <param name="request"><see cref="HttpRequest"/> 对象</param> private static void BeginLogMvcRequest(MvcRequest model, HttpRequest request) { if (model == null || request == null) { return; } var _path = GetLogPath("request.txt"); //允许多个线程同时写入 using (var fileStream = new FileStream(_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { var streamWrite = new StreamWriter(fileStream, Encoding.Default); try { streamWrite.BaseStream.Seek(0, SeekOrigin.End); streamWrite.WriteLine(DateTime.Now.ToFormatDateTime()); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n 请求信息:"); streamWrite.WriteLine($"\r\n\t浏览器标识:{model.UserAgent}"); streamWrite.WriteLine($"\r\n\t请求地址:{model.Url}"); streamWrite.WriteLine($"\r\n\t请求参数:{model.Params}"); streamWrite.WriteLine($"\r\n\t请求类型:{model.RequestType}"); streamWrite.WriteLine($"\r\n\t控制器名:{model.ControllerName}"); streamWrite.WriteLine($"\r\n\tAction名:{model.ActionName}"); streamWrite.WriteLine($"\r\n\tIp 地址:{model.IpAddress}"); streamWrite.WriteLine($"\r\n\t线程 ID:{model.ThreadId}"); streamWrite.WriteLine($"\r\n\t消耗时间:{model.ConsumingTime} s"); //日志分隔线 streamWrite.WriteLine("--------------------------------------------------------------------------------------------------------------\n"); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n"); streamWrite.WriteLine("\r\n"); } finally { streamWrite.Flush(); streamWrite.Close(); } } }
/// <summary> /// Calls the sub class's <c>OnExecute</c> method to perform the desired /// action, then transfers control to the target page for rendering. /// </summary> /// <param name="request">The <c>MvcRequest</c> the command is being /// executed for.</param> public void Execute( MvcRequest request) { // perform any pre-execute initialization this.Init(request); // call the abstract OnExecute implemented by the sub-class this.OnExecute(request); if (this.doRedirect) { // get the target page this.targetPage = this.GetTargetPage(request); // get the path of the content for the target page PageFinder.FileRecord xmlFileRec = this.GetXmlPath(request); // put the XML file info into the request context // so the page can get it if (xmlFileRec != null) { request.Items["pageXml"] = xmlFileRec.fullPath; // for backward compatibility request.Items["pageXmlFile"] = xmlFileRec; } // transfer control to the target page #if (DEBUG) this.Transfer(request); #else try { this.Transfer(request); // Server.Transfer always throws a ThreadAbortException on successful // completion, so we ignore it here } catch (ThreadAbortException) {} catch (Exception e) { Logger.GetLogger(LOGGER).ReportInnerExceptions = true; Logger.GetLogger(LOGGER).Error("RedirectingCommand.Execute - error Transferring: ", e); // TODO: transfer to error page?? } #endif } }
public static void Fill(this BaseFilter filter, MvcRequest request) { if (!string.IsNullOrEmpty(request[BaseFilterParameterNames.PAGESIZE])) { int pagesize; if (int.TryParse(request[BaseFilterParameterNames.PAGESIZE], out pagesize)) { filter.PageSize = pagesize; filter.Page = 1; } } if (!string.IsNullOrEmpty(request[BaseFilterParameterNames.PAGE])) { if (filter.PageSize.HasValue) { int page; if (int.TryParse(request[BaseFilterParameterNames.PAGE], out page)) { filter.Page = page; } } else { LogManager.GetCurrentClassLogger().Warn(warn => warn("Call to set the page on filter, but since could not get pagesize the page is reset to null.")); } } }
public static string GetLanguage( MvcRequest request, string site) { //HttpRequest request = HttpContext.Current.Request; string lang = null; // try to get language setting from cookie try { if (request.GetCookie(MVC_COOKIE_COLLECTION) != null) { lang = request.GetCookie(MVC_COOKIE_COLLECTION)[LANGUAGE_COOKIE]; } // try to get language setting from request's UserLanguages // ?? do we want to use this method?? // if (lang == null) { // string userLang = request.UserLanguages[0]; // if (userLang[2] == '-') { // lang = userLang.Substring(0, 2); // } else { // } // } } catch { int k = 0; } if (lang == null) { XmlConfiguration siteConfig = SitesConfig.GetInstance().GetConfig("sites", site.ToUpper()); if (siteConfig != null) { lang = siteConfig.GetValue("//defaultLanguage"); } } // TODO: determine how to put language back in as a cookie //request.[MVC_COOKIE_COLLECTION][LANGUAGE_COOKIE] = lang; return lang; }
/// <summary> /// Evaluates the rule for the given request. The <b>AndRule</b> accumulates the /// results of all of its child rules. It evaluates all of the child rules /// regardless of whether or not any particular rule passes or fails. /// </summary> /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param> /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the /// rule and any validation errors that occurred.</returns> public override ValidationResult Evaluate( MvcRequest request) { ValidationResult result = new ValidationResult(); foreach (IValidationRule rule in children) { // evaluate the child rule ValidationResult childResult = rule.Evaluate(request); // if the child rule failed, set this rule to failure and add the // error(s) from the child if (!childResult.Passed) { result.Passed = false; result.AddErrors(childResult.Errors); if (rule.StopOnFail || childResult.StopProcessing) { result.StopProcessing = true; break; } } } return result; }
/// <summary> /// Evaluates the rule for the given request. The <b>OrRule</b> short circuits /// on the first successful child rule, with a passed status. /// </summary> /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param> /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the /// rule and any validation errors that occurred.</returns> public override ValidationResult Evaluate( MvcRequest request) { ValidationResult result = new ValidationResult { Passed = false }; // TODO: if cnt is 0 should we return true or false?? int cnt = children.Count; for (int k = 0; k < cnt && !result.Passed; k++) { IValidationRule rule = children[k]; // evaluate the child rule ValidationResult childResult = rule.Evaluate(request); // clear out any previous validation errors result.ClearErrors(); // if the child rule passed, set this rule to passed, // if not, add the errors from the child to the OrRule's result if (childResult.Passed) { result.Passed = true; } else { result.AddErrors(childResult.Errors); if (rule.StopOnFail || childResult.StopProcessing) { result.StopProcessing = true; break; } } } // if the OrRule did not pass and the is a specific error identified // for the OrRule, replace any errors from the children with the one // for the OrRule if (!result.Passed && (ErrorId != 0)) { result.ClearErrors(); result.AddError(Field, ErrorId); } return result; }
public static void Fill( this AccountFilter filter, MvcRequest request) { if (!string.IsNullOrEmpty(request[ParameterNames.Account.ID])) { filter.Ids = request[ParameterNames.Account.ID].ToGuidArray(); } else if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.ID])) { filter.Ids = request[ParameterNames.Account.Filter.ID].ToGuidArray(); } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.USERNAME])) { filter.Usernames = request[ParameterNames.Account.Filter.USERNAME].ToStringArray(); } else if ( Array.FindAll<string>(request.Params.AllKeys, key => (key != null) && key.StartsWith(ParameterNames.Account.Filter.USERNAME)).Length == 1 ) { // Perform more specific like filtering on attributes, append wildcards as needed. Only allowed for sinlge username search string usernameParam = Array.FindAll<string>(request.Params.AllKeys, key => (key != null) && key.StartsWith(ParameterNames.Account.Filter.USERNAME))[0]; string relation = usernameParam.Substring(ParameterNames.Account.Filter.USERNAME.Length + 1, usernameParam.Length - (ParameterNames.Account.Filter.USERNAME.Length + 1) ); filter.Usernames = GenerateUsernameRelationType(request[usernameParam].ToStringArray(), relation); } else if (!string.IsNullOrEmpty(request[ParameterNames.Account.USERNAME])) { filter.Usernames = request[ParameterNames.Account.USERNAME].ToStringArray(); } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.ROLE])) { filter.RoleNames = request[ParameterNames.Account.Filter.ROLE].ToStringArray(); } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.PERSONNAME])) { filter.Name = request[ParameterNames.Account.Filter.PERSONNAME]; } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.MODIFIED_DATE])) { DateTime date; if (DateTime.TryParse(request[ParameterNames.Account.Filter.MODIFIED_DATE], out date)) { filter.ModifiedDate = date; } } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.CREATED_DATE])) { DateTime date; if (DateTime.TryParse(request[ParameterNames.Account.Filter.CREATED_DATE], out date)) { filter.CreatedDate = date; } } // attributes // TODO: should add support for specifying null -- "[null]"? // find any attribute parameters in the params collection // attribute parameter names are of the form: filter_account_attribute_[relation]_[attributeCode] string[] attrParams = Array.FindAll<string>(request.Params.AllKeys, key => (key != null) && key.StartsWith(ParameterNames.Account.Filter.ATTRIBUTE_PREFIX)); // if we found attribute parameters, process them if ((attrParams != null) && (attrParams.Length > 0)) { List<AccountFilter.AttributeFilter> attributeCriteria = new List<AccountFilter.AttributeFilter>(); string[] relations = ACCOUNT_ATTRIBUTE_RELATIONS.Split(','); foreach (string paramName in attrParams) { // skip it if there is no value if (!string.IsNullOrEmpty(request[paramName])) { int prefixLen = ParameterNames.Account.Filter.ATTRIBUTE_PREFIX.Length + 3; // get the relation string relation = paramName.Substring(ParameterNames.Account.Filter.ATTRIBUTE_PREFIX.Length, 2).ToLower(); AccountFilter.AttributeFilter val = new AccountFilter.AttributeFilter { AttributeCode = paramName.Remove(0, prefixLen), Value = request[paramName], Relation = TranslateRelation(relation) }; attributeCriteria.Add(val); } } filter.Attributes = attributeCriteria; } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.LATITUDE])) { filter.Latitude = request[ParameterNames.Account.Filter.LATITUDE]; } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.LONGITUDE])) { filter.Longitude = request[ParameterNames.Account.Filter.LONGITUDE]; } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.RADIUS])) { filter.Radius = request[ParameterNames.Account.Filter.RADIUS]; } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.STATUS])) { string status = request[ParameterNames.Account.Filter.STATUS].ToString(); filter.Status = DaoFactory.GetDao<IAccountStatusDao>().Get(status); } else { filter.Status = DaoFactory.GetDao<IAccountStatusDao>().Get("active"); } if (!string.IsNullOrEmpty(request[ParameterNames.Account.Filter.NAME_SORT])) { filter.NameSort = request[ParameterNames.Account.Filter.NAME_SORT]; } ((BaseFilter)filter).Fill(request); }
public static void Fill( this AttributeTypeFilter filter, MvcRequest request) { if (!string.IsNullOrEmpty(request[ParameterNames.AttributeType.ID])) { filter.Ids = request[ParameterNames.AttributeType.ID].ToIntArray(); } if (!string.IsNullOrEmpty(request[ParameterNames.AttributeType.CODE])) { filter.Codes = request[ParameterNames.AttributeType.CODE].ToStringArray(); } ((BaseFilter)filter).Fill(request); }
public void SetRequest(MvcRequest req) { CurrentRequest.setRequest(req); }
private IState GetStartState( MvcRequest request) { long? curStateId = null; bool useStateParam = false; // get the setting from the config for whether or not to get the state // ID from the "st" parameter try { if (ConfigurationManager.AppSettings["useStateParam"] != null) { useStateParam = bool.Parse(ConfigurationManager.AppSettings["useStateParam"]); } } catch {} // try getting the state from the request, if needed if (useStateParam) { try { curStateId = long.Parse(request[STATE_PARAM_NAME]); } catch {} } // if we don't have a start state yet, try getting it from session if (!curStateId.HasValue) { try { // TODO: this should NOT reference HttpContext! curStateId = long.Parse((string)SessionStateProvider.GetSessionState()[CUR_STATE_NAME]); } catch {} } // if we still don't have a start state, try getting it from the cookie if (!curStateId.HasValue) { try { curStateId = long.Parse(request.GetCookie(CUR_STATE_NAME).Value); } catch {} } // as a last resort, try the parameter if we didn't already if ((!curStateId.HasValue) && !useStateParam) { try { curStateId = long.Parse(request[STATE_PARAM_NAME]); } catch {} } if (!curStateId.HasValue) { LogManager.GetCurrentClassLogger().Error( errorMessage => errorMessage("DoTransitionCommand: State or Event missing.")); throw new ApplicationException("Start State is missing."); } IState startState = StateManager.GetInstance().GetState(curStateId.Value); if (!(startState is StartState)) { throw new ApplicationException("State is not a StartState: startState= " + startState.Id); } return startState; }
/// <summary> /// Carries out the actions required to execute the command. /// </summary> /// <param name="request">The <c>MvcRequest</c> request /// that triggered the command to be executed.</param> public void Execute( MvcRequest request) { string startEvent = request[EVENT_PARAM_NAME].ToLower(); // get the starting start for the request IState startState = this.GetStartState(request); ContentProvider contentProvider = null; try { string content = null; // make the context for the request TransitionContext context = new TransitionContext(startState, startEvent, ((PageState)startState).Site, request); // make a ContentProvider for the request contentProvider = ContentProviderFactory.Make(context); // get a Publisher from the ContentProvider Publisher publisher = contentProvider.GetPublisher(); // assume we need to perform the transition(s). if published // content is sucessfully used, we'll set this to false. bool doTransitions = true; // make sure we got a publisher if (publisher != null) { // generate a publish key and remember it in the context context.PublishKey = publisher.MakeKey(context); // determine if we have publihsed content to fulfill this request // and if we should use it if (publisher.UsePublishedContent(context.PublishKey, context)) { // if so, get it content = contentProvider.GetPublishedContent(context); // if there is no published content, do the transitions if (content != null) { doTransitions = false; } } } // if we didn't use published content, we need to generate the content // by performing the transitions if (doTransitions) { // put the TransitionContext into the request context so Page can get it request.Items["transitionContext"] = context; // perform the transition(s) StateTransitioner transitioner = new StateTransitioner(); IState targetState = transitioner.DoTransition(startState, startEvent, context); // target state should be an EndState if (targetState is EndState) { context.EndState = targetState; request.Items["targetStateId"] = targetState.Id; request.Items["targetState"] = targetState; } else { // TODO: what if targgetState is not an EndState? LogManager.GetCurrentClassLogger().Warn( warn => warn("Target state {0}{1} is not an EndState.", targetState.Id, string.IsNullOrEmpty(targetState.Name) ? "" : " [" + targetState.Name + "]")); } // save the ending state to the session and cookie try { //HttpSessionState session = HttpContext.Current.Session; if (SessionStateProvider.GetSessionState() != null) { SessionStateProvider.GetSessionState()[CUR_STATE_NAME] = targetState.Id; } } catch { } try { //request.SetResponseCookie(new MvcCookie(CUR_STATE_NAME, targetState.Id.ToString())); } catch { } // determine if the content generated to fulfill the request should // be published for use by future requests if ((publisher != null) && publisher.ShouldBePublished(context)) { content = contentProvider.RenderPublishContent(context); // TODO: what if "content" is not string?? // should RenderPublishContent throw exception if no publish call wanted? if (content != null) { publisher.Publish(content, context); } } else { content = contentProvider.RenderContent(context); } } if (content != null) { request.WriteResponse(content, false); } } catch (ThreadAbortException) { // ignore this one, since when a .aspx page is creating a new thread // and killing the current thread thus throwing this exception } catch (Exception e) { LogManager.GetCurrentClassLogger().Error( errorMessage => errorMessage("Could not execute the command. "), e); //since we cant do anything about this here, rethrow. throw; } finally { if (contentProvider != null) { contentProvider.Dispose(); } } }
/// <summary> /// Determines whether or not the system should be forced to use dynamic content /// regardless of existance of published content. /// </summary> /// <param name="request">The <b>MvcRequest</b> the determination is being made for.</param> /// <returns><b>True</b> to force dynamic content to be returned to the client, /// or <b>false</b> if published content can be used if it's available.</returns> public virtual bool UseDynamicContent( MvcRequest request) { return false; }
public static Person CreatePerson(MvcRequest request) { return Populate(request, new Person()); }
/// <summary> /// Creates a new <c>Media</c> from the request. /// </summary> /// <param name="request">Request to create the Media from.</param> /// <returns>A populated Media object.</returns> public static Model.Media CreateMedia(MvcRequest request) { return new Model.Media() { //TODO {INIT_PARAMS} }; }
/// <summary> /// 记录Mvc请求信息 /// </summary> /// <param name="model"><see cref="MvcRequest"/> 对象</param> /// <param name="request"><see cref="HttpRequest"/> 对象</param> public static void LogMvcRequest(MvcRequest model, HttpRequest request) => new AsyncLogMvcRequest(BeginLogMvcRequest).BeginInvoke(model, request, null, null);
public static Account Populate(MvcRequest request, Account account) { //if the username has been defined in the request #region DEPRCIATED if (!string.IsNullOrEmpty(request[ParameterNames.Account.USERNAME])) { // This will only update the first username in the collection, // needs to be updated to update any. if (account.Usernames.Count > 0) { if (account.Usernames[0] != null) { account.Usernames[0].Value = request[ParameterNames.Account.USERNAME]; } else { account.Usernames[0] = new Username { Value = request[ParameterNames.Account.USERNAME] }; } } else { account.Usernames.Add(new Username { Value = request[ParameterNames.Account.USERNAME] }); } } #endregion //if the username has been defined in the request if (!string.IsNullOrEmpty(request[ParameterNames.Account.Field.USERNAME])) { // This will only update the first username in the collection, // needs to be updated to update any. if (account.Usernames.Count > 0) { if (account.Usernames[0] != null) { account.Usernames[0].Value = request[ParameterNames.Account.Field.USERNAME]; } else { account.Usernames[0] = new Username { Value = request[ParameterNames.Account.Field.USERNAME] }; } } else { account.Usernames.Add(new Username { Value = request[ParameterNames.Account.Field.USERNAME] }); } } if (account.Person != null) { Populate(request, account.Person); }else { account.Person = new Person(); Populate(request, account.Person); } #region DEPRECIATED if (!string.IsNullOrEmpty(request[ParameterNames.Account.PASSWORD])) { account.Password = request[ParameterNames.Account.PASSWORD]; } #endregion if (!string.IsNullOrEmpty(request[ParameterNames.Account.Field.PASSWORD])) { account.Password = request[ParameterNames.Account.Field.PASSWORD]; } if (!string.IsNullOrEmpty(request[ParameterNames.AccountStatus.CODE])) { AccountStatus accountStatus = DaoFactory.GetDao<IAccountStatusDao>().Get(request[ParameterNames.AccountStatus.CODE]); account.Status = accountStatus; } return account; }
/// <summary> /// 记录Mvc请求信息 /// </summary> /// <param name="model"><see cref="MvcRequest"/> 对象</param> public static void LogMvcRequest(MvcRequest model) => new AsyncLogMvcRequest(BeginLogMvcRequest).BeginInvoke(model, HttpContext.Current, null, null);
/// <summary> /// Determines whether or not the published content should be forced to be regenerated. /// </summary> /// <param name="request">The <b>MvcRequest</b> the determination is being made for.</param> /// <returns><b>True</b> if the published content should be force to be regenerated, /// or <b>false</b> if not.</returns> public virtual bool ForceRepublish( MvcRequest request) { return false; }