protected virtual ControllerConfiguration LoadConfig(string controllerName) { ControllerConfiguration config = null; if (!(_controllers.TryGetValue(controllerName, out config))) { config = DataControllerBase.CreateConfigurationInstance(GetType(), controllerName); _controllers[controllerName] = config; } return(config); }
ControllerConfiguration IPlugIn.Create(ControllerConfiguration config) { if (config.Navigator.CanEdit) { return(config); } XmlDocument document = new XmlDocument(); document.LoadXml(config.Navigator.OuterXml); return(new ControllerConfiguration(document.CreateNavigator())); }
public ControllerConfiguration Virtualize(string controllerName) { ControllerConfiguration config = this; if (!(_navigator.CanEdit)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(_navigator.OuterXml); config = new ControllerConfiguration(doc.CreateNavigator()); } return(config); }
protected virtual void ProcessResult(ControllerConfiguration config, ActionResult result) { if (_pk != null) { foreach (FieldValue fv in result.Values) { if (fv.Name == _pk.Name) { ResolvePrimaryKey(config.ControllerName, fv.Name, _pk.Value, fv.Value); break; } } } }
public ControllerConfiguration Virtualize(string controllerName) { ControllerConfiguration config = this; if (!(_navigator.CanEdit)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(_navigator.OuterXml); config = new ControllerConfiguration(doc.CreateNavigator()); } BusinessRules rules = CreateBusinessRules(); if (rules != null) { rules.VirtualizeController(controllerName, config._navigator, config._namespaceManager); } return(config); }
public void AssignContext(string controller, string view, ControllerConfiguration config) { _controller = controller; _view = view; string referrer = String.Empty; if ((PageSize == 1000) && String.IsNullOrEmpty(this.SortExpression)) { // we are processing a request to retrieve static lookup data XPathNavigator sortExpressionNode = config.SelectSingleNode("c:dataController/c:views/c:view[@id=\'{0}\']/@sortExpression", view); if ((sortExpressionNode != null) && !(String.IsNullOrEmpty(sortExpressionNode.Value))) { this.SortExpression = sortExpressionNode.Value; } } if ((HttpContext.Current != null) && (HttpContext.Current.Request.UrlReferrer != null)) { referrer = HttpContext.Current.Request.UrlReferrer.AbsolutePath; } this._contextKey = string.Format("{0}/{1}.{2}.{3}", referrer, controller, view, ContextKey); }
protected virtual void ProcessResult(ControllerConfiguration config, ActionResult result) { if (_pk == null) { foreach (var fvo in result.Values) { _commitResult.Values.Add(new ControllerFieldValue(config.ControllerName, fvo.Name, fvo.OldValue, fvo.NewValue)); } } else { foreach (var fvo in result.Values) { if (fvo.Name == _pk.Name) { ResolvePrimaryKey(config.ControllerName, fvo.Name, _pk.Value, fvo.Value); break; } } } }
public static List<UriRestConfig> Enumerate(ControllerConfiguration config) { List<UriRestConfig> list = new List<UriRestConfig>(); XPathNavigator restConfigNode = config.SelectSingleNode("/c:dataController/c:restConfig"); if (restConfigNode != null) { UriRestConfig urc = null; // configuration regex: ^\s*(?'Property'\w+)\s*(:|=)\s*(?'Value'.+?)\s*$ Match m = Regex.Match(restConfigNode.Value, "^\\s*(?\'Property\'\\w+)\\s*(:|=)\\s*(?\'Value\'.+?)\\s*$", (RegexOptions.IgnoreCase | RegexOptions.Multiline)); while (m.Success) { string propertyName = m.Groups["Property"].Value; string propertyValue = m.Groups["Value"].Value; if (propertyName.Equals("Uri", StringComparison.CurrentCultureIgnoreCase)) try { urc = new UriRestConfig(propertyValue); list.Add(urc); } catch (Exception ) { } else if (urc != null) urc[propertyName] = propertyValue; m = m.NextMatch(); } } return list; }
private void ExecuteActionRequest(HttpRequest request, HttpResponse response, Stream output, bool json, ControllerConfiguration config, string controllerName, string view, string key, List<string> filter, string actionGroupId, string actionId) { XPathNavigator actionNode = SelectAction(config, actionGroupId, actionId); string commandName = HttpMethodToCommandName(request); string commandArgument = String.Empty; string lastCommandName = String.Empty; if (actionNode == null) { if (String.IsNullOrEmpty(commandName)) { response.StatusCode = 404; return; } } else { commandName = actionNode.GetAttribute("commandName", String.Empty); commandArgument = actionNode.GetAttribute("commandArgument", String.Empty); lastCommandName = actionNode.GetAttribute("whenLastCommandName", String.Empty); } // prepare action arguments ActionArgs args = new ActionArgs(); args.Controller = controllerName; args.View = view; args.CommandName = commandName; args.CommandArgument = commandArgument; args.LastCommandName = lastCommandName; args.Filter = filter.ToArray(); args.SortExpression = request.QueryString["_sortExpression"]; string selectedValues = request.Params["_selectedValues"]; if (!(String.IsNullOrEmpty(selectedValues))) args.SelectedValues = selectedValues.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries); args.Trigger = request.Params["_trigger"]; args.Path = String.Format("{0}/{1}", actionGroupId, actionId); NameValueCollection form = request.Form; if (request.HttpMethod == "GET") form = request.QueryString; List<FieldValue> values = new List<FieldValue>(); foreach (string fieldName in form.Keys) { XPathNavigator field = SelectField(config, fieldName); XPathNavigator dataField = SelectDataField(config, view, fieldName); if (field != null) { object oldValue = form[(fieldName + "_OldValue")]; object value = form[fieldName]; // try parsing the values string dataFormatString = null; if (dataField != null) dataFormatString = dataField.GetAttribute("dataFormatString", String.Empty); if (String.IsNullOrEmpty(dataFormatString)) dataFormatString = field.GetAttribute("dataFormatString", String.Empty); if (!(String.IsNullOrEmpty(dataFormatString)) && !(dataFormatString.StartsWith("{"))) dataFormatString = String.Format("{{0:{0}}}", dataFormatString); string fieldType = field.GetAttribute("type", String.Empty); if (NumericTypes.Contains(fieldType)) { double d; if (Double.TryParse(((string)(value)), NumberStyles.Any, CultureInfo.CurrentUICulture, out d)) value = d; if (Double.TryParse(((string)(oldValue)), NumberStyles.Any, CultureInfo.CurrentUICulture, out d)) oldValue = d; } else if (fieldType == "DateTime") { DateTime dt; if (!(String.IsNullOrEmpty(dataFormatString))) { if (DateTime.TryParseExact(((string)(value)), dataFormatString, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt)) value = dt; if (DateTime.TryParseExact(((string)(oldValue)), dataFormatString, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt)) oldValue = dt; } else { if (DateTime.TryParse(((string)(value)), out dt)) value = dt; if (DateTime.TryParse(((string)(oldValue)), out dt)) oldValue = dt; } } // create a field value FieldValue fv = null; if (oldValue != null) fv = new FieldValue(fieldName, oldValue, value); else fv = new FieldValue(fieldName, value); // figure if the field is read-only bool readOnly = (field.GetAttribute("readOnly", String.Empty) == "true"); string writeRoles = field.GetAttribute("writeRoles", String.Empty); if (!(String.IsNullOrEmpty(writeRoles)) && !(DataControllerBase.UserIsInRole(writeRoles))) readOnly = true; if (dataField == null) readOnly = true; fv.ReadOnly = readOnly; // add field value to the list values.Add(fv); } } int keyIndex = 0; XPathNodeIterator keyIterator = config.Select("/c:dataController/c:fields/c:field[@isPrimaryKey=\'true\']"); while (keyIterator.MoveNext()) { string fieldName = keyIterator.Current.GetAttribute("name", String.Empty); foreach (FieldValue fv in values) if (fv.Name == fieldName) { fieldName = null; if ((fv.OldValue == null) && ((commandName == "Update") || (commandName == "Delete"))) { fv.OldValue = fv.NewValue; fv.Modified = false; } break; } if (!(String.IsNullOrEmpty(fieldName))) { string oldValue = null; if (!(String.IsNullOrEmpty(key))) { string[] keyValues = key.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries); if (keyIndex < keyValues.Length) oldValue = keyValues[keyIndex]; } values.Add(new FieldValue(fieldName, oldValue, oldValue)); } keyIndex++; } args.Values = values.ToArray(); // execute action IDataController controllerInstance = ControllerFactory.CreateDataController(); ActionResult result = controllerInstance.Execute(controllerName, view, args); // redirect response location if success or error url has been specified string successUrl = request.Params["_successUrl"]; string errorUrl = request.Params["_errorUrl"]; if ((result.Errors.Count == 0) && !(String.IsNullOrEmpty(successUrl))) { response.RedirectLocation = successUrl; response.StatusCode = 301; return; } if ((result.Errors.Count > 0) && !(String.IsNullOrEmpty(errorUrl))) { if (errorUrl.Contains("?")) errorUrl = (errorUrl + "&"); else errorUrl = (errorUrl + "?"); errorUrl = String.Format("{0}_error={1}", errorUrl, HttpUtility.UrlEncode(result.Errors[0])); response.RedirectLocation = errorUrl; response.StatusCode = 301; return; } if (json) { StreamWriter sw = CreateStreamWriter(request, response, output); BeginResponsePadding(request, sw); sw.Write("{{\"rowsAffected\":{0}", result.RowsAffected); if ((result.Errors != null) && (result.Errors.Count > 0)) { sw.Write(",\"errors\":["); bool first = true; foreach (string error in result.Errors) { if (first) first = false; else sw.Write(","); sw.Write("{{\"message\":\"{0}\"}}", BusinessRules.JavaScriptString(error)); } sw.Write("]"); } if (!(String.IsNullOrEmpty(result.ClientScript))) sw.Write(",\"clientScript\":\"{0}\"", BusinessRules.JavaScriptString(result.ClientScript)); if (!(String.IsNullOrEmpty(result.NavigateUrl))) sw.Write(",\"navigateUrl\":\"{0}\"", BusinessRules.JavaScriptString(result.NavigateUrl)); if (result.Values != null) foreach (FieldValue fv in result.Values) { sw.Write(",\"{0}\":", fv.Name); WriteJSONValue(sw, fv.Value, null); } sw.Write("}"); EndResponsePadding(request, sw); sw.Close(); } else { XmlWriter writer = CreateXmlWriter(output); writer.WriteStartDocument(); writer.WriteStartElement("result"); writer.WriteAttributeString("rowsAffected", result.RowsAffected.ToString()); if ((result.Errors != null) && (result.Errors.Count > 0)) { writer.WriteStartElement("errors"); foreach (string error in result.Errors) { writer.WriteStartElement("error"); writer.WriteAttributeString("message", error); writer.WriteEndElement(); } writer.WriteEndElement(); } if (!(String.IsNullOrEmpty(result.ClientScript))) writer.WriteAttributeString("clientScript", result.ClientScript); if (!(String.IsNullOrEmpty(result.NavigateUrl))) writer.WriteAttributeString("navigateUrl", result.NavigateUrl); if (result.Values != null) foreach (FieldValue fv in result.Values) writer.WriteElementString(fv.Name, Convert.ToString(fv.Value)); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } }
private void AnalyzeRouteValues(HttpRequest request, HttpResponse response, bool isHttpGetMethod, ControllerConfiguration config, out string view, out string key, out string fieldName, out string actionGroupId, out string actionId, out string commandName) { RouteValueDictionary routeValues = request.RequestContext.RouteData.Values; string segment1 = ((string)(routeValues["Segment1"])); string segment2 = ((string)(routeValues["Segment2"])); string segment3 = ((string)(routeValues["Segment3"])); string segment4 = ((string)(routeValues["Segment4"])); view = null; key = null; fieldName = null; actionGroupId = null; actionId = null; commandName = null; if (!(String.IsNullOrEmpty(segment1))) if (SelectView(config, segment1) != null) { view = segment1; if (isHttpGetMethod) { key = segment2; fieldName = segment3; } else if (VerifyActionSegments(config, segment2, segment3, false)) { actionGroupId = segment2; actionId = segment3; } else if (String.IsNullOrEmpty(segment2)) { if (HttpMethod != "POST") response.StatusCode = 404; } else { key = segment2; if (VerifyActionSegments(config, segment3, segment4, true)) { actionGroupId = segment3; actionId = segment4; } else if (!(((HttpMethod == "PUT") || (HttpMethod == "DELETE")))) response.StatusCode = 404; } } else if (isHttpGetMethod) { key = segment1; fieldName = segment2; } else if (VerifyActionSegments(config, segment1, segment2, false)) { actionGroupId = segment1; actionId = segment2; } else if (String.IsNullOrEmpty(segment1)) response.StatusCode = 404; else { key = segment1; if (VerifyActionSegments(config, segment2, segment3, true)) { actionGroupId = segment2; actionId = segment3; } else if (!(((HttpMethod == "PUT") || (HttpMethod == "DELETE")))) response.StatusCode = 404; } else { view = request.QueryString["_view"]; key = request.QueryString["_key"]; fieldName = request.QueryString["_fieldName"]; if (!(isHttpGetMethod)) actionGroupId = request.QueryString["_actionId"]; } if (!(isHttpGetMethod)) { XPathNavigator actionNode = SelectAction(config, actionGroupId, actionId); if (actionNode != null) commandName = actionNode.GetAttribute("commandName", String.Empty); else commandName = HttpMethodToCommandName(request); } }
protected XPathNavigator SelectView(ControllerConfiguration config, string viewId) { return config.SelectSingleNode("/c:dataController/c:views/c:view[@id=\'{0}\']", viewId); }
protected virtual void InternalProcess(ActionArgs args, ControllerConfiguration config) { bool hasCreatedByUserId = false; bool hasCreatedByUserName = false; bool hasCreatedOn = false; bool hasModifiedByUserId = false; bool hasModifiedByUserName = false; bool hasModifiedOn = false; // assign tracking values to field values passed from the client foreach (FieldValue v in args.Values) if (!(v.ReadOnly)) if (!(hasCreatedByUserId) && IsCreatedByUserIdPattern(v.Name)) { hasCreatedByUserId = true; if (v.Value == null) { v.NewValue = UserId; v.Modified = true; } } else if (!(hasCreatedByUserName) && IsCreatedByUserNamePattern(v.Name)) { hasCreatedByUserName = true; if (v.Value == null) { v.NewValue = UserName; v.Modified = true; } } else if (!(hasCreatedOn) && IsCreatedOnPattern(v.Name)) { hasCreatedOn = true; if (v.Value == null) { v.NewValue = DateTime.Now; v.Modified = true; } } else if (!(hasModifiedByUserId) && IsModifiedByUserIdPattern(v.Name)) { hasModifiedByUserId = true; v.NewValue = UserId; v.Modified = true; } else if (!(hasModifiedByUserName) && IsModifiedByUserNamePattern(v.Name)) { hasModifiedByUserName = true; v.NewValue = UserName; v.Modified = true; } else if (!(hasModifiedOn) && IsModifiedOnPattern(v.Name)) { hasModifiedOn = true; v.NewValue = DateTime.Now; v.Modified = true; } // assign missing tracking values List<FieldValue> values = new List<FieldValue>(args.Values); XPathNodeIterator fieldIterator = config.Select("/c:dataController/c:fields/c:field[not(@readOnly=\'true\')]"); while (fieldIterator.MoveNext()) { string fieldName = fieldIterator.Current.GetAttribute("name", String.Empty); // ensure that missing "created" values are provided if (args.CommandName == "Insert") if (!(hasCreatedByUserId) && IsCreatedByUserIdPattern(fieldName)) { hasCreatedByUserId = true; FieldValue v = new FieldValue(fieldName, UserId); values.Add(v); } else if (!(hasCreatedByUserName) && IsCreatedByUserNamePattern(fieldName)) { hasCreatedByUserName = true; FieldValue v = new FieldValue(fieldName, UserName); values.Add(v); } else if (!(hasCreatedOn) && IsCreatedOnPattern(fieldName)) { hasCreatedOn = true; FieldValue v = new FieldValue(fieldName, DateTime.Now); values.Add(v); } // ensure that missing "modified" values are provided if (!(hasModifiedByUserId) && IsModifiedByUserIdPattern(fieldName)) { hasModifiedByUserId = true; FieldValue v = new FieldValue(fieldName, UserId); values.Add(v); } else if (!(hasModifiedByUserName) && IsModifiedByUserNamePattern(fieldName)) { hasModifiedByUserName = true; FieldValue v = new FieldValue(fieldName, UserName); values.Add(v); } else if (!(hasModifiedOn) && IsModifiedOnPattern(fieldName)) { hasModifiedOn = true; FieldValue v = new FieldValue(fieldName, DateTime.Now); values.Add(v); } } args.Values = values.ToArray(); }
public virtual ControllerConfiguration EnsureVitalElements() { // verify that the data controller has views and actions XPathNavigator root = SelectSingleNode("/c:dataController[c:views/c:view and c:actions/c:actionGroup]"); if (root != null) { return(this); } // add missing configuration elements XmlDocument doc = new XmlDocument(); doc.LoadXml(_navigator.OuterXml); ControllerConfiguration config = new ControllerConfiguration(doc.CreateNavigator()); XPathNavigator fieldsNode = config.SelectSingleNode("/c:dataController/c:fields[not(c:field[@isPrimaryKey=\'true\'])]"); if (fieldsNode != null) { fieldsNode.AppendChild("<field name=\"PrimaryKey\" type=\"Int32\" isPrimaryKey=\"true\" readOnly=\"true\"/>"); } root = config.SelectSingleNode("/c:dataController"); EnsureChildNode(root, "views"); XPathNavigator viewsNode = config.SelectSingleNode("/c:dataController/c:views[not(c:view)]"); if (viewsNode != null) { StringBuilder sb = new StringBuilder("<view id=\"view1\" type=\"Form\" label=\"Form\"><categories><category id=\"c1\" flow=\"New" + "Column\"><dataFields>"); XPathNodeIterator fieldIterator = config.Select("/c:dataController/c:fields/c:field"); while (fieldIterator.MoveNext()) { string fieldName = fieldIterator.Current.GetAttribute("name", String.Empty); bool hidden = (fieldName == "PrimaryKey"); string length = fieldIterator.Current.GetAttribute("length", String.Empty); if (String.IsNullOrEmpty(length) && (((bool)(fieldIterator.Current.Evaluate("not(c:items/@style!=\'\')", _resolver))) == true)) { if (fieldIterator.Current.GetAttribute("type", String.Empty) == "String") { length = "50"; } else { length = "20"; } } sb.AppendFormat("<dataField fieldName=\"{0}\" hidden=\"{1}\"", fieldName, hidden.ToString().ToLower()); if (!(String.IsNullOrEmpty(length))) { sb.AppendFormat(" columns=\"{0}\"", length); } sb.Append(" />"); } sb.Append("</dataFields></category></categories></view>"); viewsNode.AppendChild(sb.ToString()); } EnsureChildNode(root, "actions"); XPathNavigator actionsNode = config.SelectSingleNode("/c:dataController/c:actions[not(c:actionGroup)]"); if (actionsNode != null) { actionsNode.AppendChild(@"<actionGroup id=""ag1"" scope=""Form""> <action id=""a1"" commandName=""Confirm"" causesValidation=""true"" whenLastCommandName=""New"" /> <action id=""a2"" commandName=""Cancel"" whenLastCommandName=""New"" /> <action id=""a3"" commandName=""Confirm"" causesValidation=""true"" whenLastCommandName=""Edit"" /> <action id=""a4"" commandName=""Cancel"" whenLastCommandName=""Edit"" /> <action id=""a5"" commandName=""Edit"" causesValidation=""true"" /> </actionGroup>"); } XPathNavigator plugIn = config.SelectSingleNode("/c:dataController/@plugIn"); if (plugIn != null) { plugIn.DeleteSelf(); config._plugIn = null; } return(config); }
public ControllerConfiguration Virtualize(string controllerName) { ControllerConfiguration config = this; if (!(_navigator.CanEdit)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(_navigator.OuterXml); config = new ControllerConfiguration(doc.CreateNavigator()); } BusinessRules rules = CreateBusinessRules(); if (rules != null) rules.VirtualizeController(controllerName, config._navigator, config._namespaceManager); return config; }
public string ToJson() { ControllerConfiguration config = this.Virtualize(this.ControllerName); Complete(); XPathNodeIterator ruleIterator = config.Select("/c:dataController/c:businessRules/c:rule"); bool newOnServer = false; bool calculateOnServer = false; while (ruleIterator.MoveNext()) { string type = ruleIterator.Current.GetAttribute("type", String.Empty); string commandName = ruleIterator.Current.GetAttribute("commandName", String.Empty); if (type != "JavaScript") { if ((commandName == "New") && !(newOnServer)) { newOnServer = true; config.SelectSingleNode("/c:dataController").CreateAttribute(String.Empty, "newOnServer", null, "true"); } else if ((commandName == "Calculate") && !(calculateOnServer)) { calculateOnServer = true; config.SelectSingleNode("/c:dataController").CreateAttribute(String.Empty, "calculateOnServer", null, "true"); } } } string expressions = JArray.FromObject(this.Expressions).ToString(); string[] exceptions = new string[] { "//comment()", "c:dataController/c:commands", "c:dataController/@handler", "//c:field/c:formula", "//c:businessRules/c:rule[@type=\"Code\" or @type=\"Sql\" or @type=\"Email\"]", "//c:businessRules/c:rule/text()", "//c:validate", "//c:styles", "//c:visibility", "//c:readOnly", "//c:expression" }; foreach (string ex in exceptions) { List <XPathNavigator> toDelete = new List <XPathNavigator>(); XPathNodeIterator iterator = config.Select(ex); while (iterator.MoveNext()) { toDelete.Add(iterator.Current.Clone()); } foreach (XPathNavigator node in toDelete) { node.DeleteSelf(); } } // special case of items/item serialization XPathNodeIterator itemsIterator = config.Select("//c:items[c:item]"); while (itemsIterator.MoveNext()) { StringBuilder lovBuilder = new StringBuilder("<list>"); XPathNodeIterator itemIterator = itemsIterator.Current.SelectChildren(XPathNodeType.Element); while (itemIterator.MoveNext()) { lovBuilder.Append(itemIterator.Current.OuterXml); } lovBuilder.Append("</list>"); itemsIterator.Current.InnerXml = lovBuilder.ToString(); } // load custom view layouts XPathNodeIterator viewIterator = config.Select("//c:views/c:view"); while (viewIterator.MoveNext()) { string layout = LoadLayout(viewIterator.Current.GetAttribute("id", String.Empty)); if (!(String.IsNullOrEmpty(layout))) { viewIterator.Current.AppendChild(String.Format("<layout><![CDATA[{0}]]></layout>", layout)); } } // extend JSON with "expressions" string json = XmlConverter.ToJson(config.Navigator, "dataController", true, "commands", "output", "fields", "views", "categories", "dataFields", "actions", "actionGroup", "businessRules", "list"); Match eof = Regex.Match(json, "\\}\\s*\\}\\s*$"); json = (json.Substring(0, eof.Index) + (",\"expressions\":" + (expressions + eof.Value))); return(json); }
public virtual void SelectView(string controller, string view) { _config = CreateConfiguration(controller); XPathNodeIterator iterator = null; if (String.IsNullOrEmpty(view)) iterator = _config.Select("/c:dataController/c:views/c:view[1]"); else iterator = _config.Select("/c:dataController/c:views/c:view[@id=\'{0}\']", view); if (!(iterator.MoveNext())) { iterator = _config.Select("/c:dataController/c:views/c:view[1]"); if (!(iterator.MoveNext())) throw new Exception(String.Format("The view \'{0}\' does not exist.", view)); } _view = iterator.Current; _viewId = iterator.Current.GetAttribute("id", String.Empty); if (!(ViewOverridingDisabled)) { XPathNodeIterator overrideIterator = _config.Select("/c:dataController/c:views/c:view[@virtualViewId=\'{0}\']", _viewId); while (overrideIterator.MoveNext()) { string viewId = overrideIterator.Current.GetAttribute("id", String.Empty); BusinessRules rules = _config.CreateBusinessRules(); if ((rules != null) && rules.IsOverrideApplicable(controller, viewId, _viewId)) { _view = overrideIterator.Current; break; } } } _viewType = iterator.Current.GetAttribute("type", String.Empty); string accessType = iterator.Current.GetAttribute("access", String.Empty); if (String.IsNullOrEmpty(accessType)) accessType = "Private"; if (!(ValidateViewAccess(controller, _viewId, accessType))) throw new Exception(String.Format("Not authorized to access private view \'{0}\' in data controller \'{1}\'. Set \'Access" + "\' property of the view to \'Public\' or enable \'Idle User Detection\' to automatica" + "lly logout user after a period of inactivity.", _viewId, controller)); }
public static void EnsureTrackingFields(ViewPage page, ControllerConfiguration config) { EventTracker tracker = new EventTracker(); tracker.InternalEnsureTrackingFields(page, config); }
public static void Process(ActionArgs args, ControllerConfiguration config) { if ((args.CommandName == "Update") || (args.CommandName == "Insert")) { EventTracker tracker = new EventTracker(); tracker.InternalProcess(args, config); } }
private bool VerifyActionSegments(ControllerConfiguration config, string actionGroupId, string actionId, bool keyIsAvailable) { bool result = true; if (SelectActionGroup(config, actionGroupId) != null) { XPathNavigator actionNode = SelectAction(config, actionGroupId, actionId); if (actionNode == null) result = false; else if (!(keyIsAvailable) && ((actionNode.GetAttribute("whenKeySelected", String.Empty) == "true") || Regex.IsMatch(actionNode.GetAttribute("commandName", String.Empty), "^(Update|Delete)$"))) result = false; } else result = false; return result; }
protected virtual void ProcessArguments(ControllerConfiguration config, ActionArgs args) { if (args.Values == null) { return; } var values = new FieldValueDictionary(args); _pk = null; // detect negative primary keys var pkNav = config.SelectSingleNode("/c:dataController/c:fields/c:field[@isPrimaryKey=\'true\']"); if (pkNav != null) { FieldValue fvo = null; if (values.TryGetValue(pkNav.GetAttribute("name", string.Empty), out fvo)) { var value = 0; if ((fvo.Value != null) && int.TryParse(Convert.ToString(fvo.Value), out value)) { if (value < 0) { if (args.CommandName == "Insert") { // request a new row from business rules var newRowRequest = new PageRequest(); newRowRequest.Controller = args.Controller; newRowRequest.View = args.View; newRowRequest.Inserting = true; newRowRequest.RequiresMetaData = true; newRowRequest.MetadataFilter = new string[] { "fields" }; var page = ControllerFactory.CreateDataController().GetPage(newRowRequest.Controller, newRowRequest.View, newRowRequest); if (page.NewRow != null) { for (var i = 0; (i < page.NewRow.Length); i++) { var newValue = page.NewRow[i]; if (newValue != null) { var field = page.Fields[i]; if (field.IsPrimaryKey) { // resolve the value of the primary key ResolvePrimaryKey(args.Controller, fvo.Name, value, newValue); value = 0; fvo.NewValue = newValue; } else { // inject a missing default value in the arguments FieldValue newFieldValue = null; if (values.TryGetValue(field.Name, out newFieldValue)) { if (!newFieldValue.Modified) { newFieldValue.NewValue = newValue; newFieldValue.Modified = true; } } else { var newValues = new List <FieldValue>(args.Values); newFieldValue = new FieldValue(field.Name, newValue); newValues.Add(newFieldValue); args.Values = newValues.ToArray(); values[field.Name] = newFieldValue; } } } } } } // resolve the primary key after the command execution if (value < 0) { if (args.CommandName == "Insert") { if (pkNav.SelectSingleNode("c:items/@dataController", config.Resolver) == null) { _pk = new FieldValue(fvo.Name, value); fvo.NewValue = null; fvo.Modified = false; } } else { // otherwise try to resolve the primary key object resolvedKey = null; if (_resolvedKeys.TryGetValue(string.Format("{0}${1}", args.Controller, fvo.Value), out resolvedKey)) { if (fvo.Modified) { fvo.NewValue = resolvedKey; } else { fvo.OldValue = resolvedKey; } } } } } } } } // resolve negative foreign keys if (_resolvedKeys.Count > 0) { var fkIterator = config.Select("/c:dataController/c:fields/c:field[c:items/@dataController]"); while (fkIterator.MoveNext()) { FieldValue fvo = null; if (values.TryGetValue(fkIterator.Current.GetAttribute("name", string.Empty), out fvo)) { var itemsDataControllerNav = fkIterator.Current.SelectSingleNode("c:items/@dataController", config.Resolver); object resolvedKey = null; if (_resolvedKeys.TryGetValue(string.Format("{0}${1}", itemsDataControllerNav.Value, fvo.Value), out resolvedKey)) { if (fvo.Modified) { fvo.NewValue = resolvedKey; } else { fvo.OldValue = resolvedKey; } } } } } // scan resolved primary keys and look for the one that are matching the keys referenced in SelectedValues, ExternalFilter, or Filter of the action foreach (var resolvedKeyInfo in _resolvedKeys.Keys) { var separatorIndex = resolvedKeyInfo.IndexOf("$"); var resolvedController = resolvedKeyInfo.Substring(0, separatorIndex); var unresolvedKeyValue = resolvedKeyInfo.Substring((separatorIndex + 1)); object resolvedKeyValue = null; if ((args.Controller == resolvedController) && _resolvedKeys.TryGetValue(resolvedKeyInfo, out resolvedKeyValue)) { var resolvedKeyValueAsString = resolvedKeyValue.ToString(); // resolve primary key references in SelectedValues if (args.SelectedValues != null) { for (var selectedValueIndex = 0; (selectedValueIndex < args.SelectedValues.Length); selectedValueIndex++) { var selectedKey = Regex.Split(args.SelectedValues[selectedValueIndex], ","); for (var keyValueIndex = 0; (keyValueIndex < selectedKey.Length); keyValueIndex++) { if (selectedKey[keyValueIndex] == unresolvedKeyValue) { selectedKey[keyValueIndex] = resolvedKeyValueAsString; args.SelectedValues[selectedValueIndex] = string.Join(",", selectedKey); selectedKey = null; break; } } if (selectedKey == null) { break; } } } } } }
protected virtual void ProcessArguments(ControllerConfiguration config, ActionArgs args) { if (args.Values == null) { return; } FieldValueDictionary values = new FieldValueDictionary(args); _pk = null; // detect negative primary keys XPathNavigator pkNav = config.SelectSingleNode("/c:dataController/c:fields/c:field[@isPrimaryKey=\'true\']"); if (pkNav != null) { FieldValue fv = null; if (values.TryGetValue(pkNav.GetAttribute("name", String.Empty), out fv)) { int value = 0; if ((fv.NewValue != null) && int.TryParse(Convert.ToString(fv.NewValue), out value)) { if (value < 0) { if (args.CommandName == "Insert") { // request a new row from business rules PageRequest newRowRequest = new PageRequest(); newRowRequest.Controller = args.Controller; newRowRequest.View = args.View; newRowRequest.Inserting = true; newRowRequest.RequiresMetaData = true; newRowRequest.MetadataFilter = new string[] { "fields" }; ViewPage page = ControllerFactory.CreateDataController().GetPage(newRowRequest.Controller, newRowRequest.View, newRowRequest); if (page.NewRow != null) { for (int i = 0; (i < page.NewRow.Length); i++) { object newValue = page.NewRow[i]; if (newValue != null) { DataField field = page.Fields[i]; if (field.IsPrimaryKey) { // resolve the value of the primary key ResolvePrimaryKey(args.Controller, fv.Name, value, newValue); value = 0; fv.NewValue = newValue; } else { // inject a missing default value in the arguments FieldValue newFieldValue = null; if (values.TryGetValue(field.Name, out newFieldValue)) { if (!(newFieldValue.Modified)) { newFieldValue.NewValue = newValue; newFieldValue.Modified = true; } } else { List <FieldValue> newValues = new List <FieldValue>(args.Values); newFieldValue = new FieldValue(field.Name, newValue); newValues.Add(newFieldValue); args.Values = newValues.ToArray(); values[field.Name] = newFieldValue; } } } } } } // resolve the primary key after the command execution if (value < 0) { _pk = new FieldValue(fv.Name, value); fv.NewValue = null; fv.Modified = false; } } } } } // resolve negative foreign keys if (_resolvedKeys.Count > 0) { XPathNodeIterator fkIterator = config.Select("/c:dataController/c:fields/c:field[c:items/@dataController]"); while (fkIterator.MoveNext()) { FieldValue fv = null; if (values.TryGetValue(fkIterator.Current.GetAttribute("name", String.Empty), out fv)) { XPathNavigator itemsDataControllerNav = fkIterator.Current.SelectSingleNode("c:items/@dataController", config.Resolver); object resolvedKey = null; if (_resolvedKeys.TryGetValue(String.Format("{0}${1}", itemsDataControllerNav.Value, fv.NewValue), out resolvedKey)) { fv.NewValue = resolvedKey; } } } } }
public virtual CommitResult Commit(JArray log) { _commitResult = new CommitResult(); try { if (log.Count > 0) { using (DataConnection connection = new DataConnection(LoadConfig(((string)(log[0]["controller"]))).ConnectionStringName, true)) { int index = -1; int sequence = -1; int lastSequence = sequence; string transactionScope = ((string)(ApplicationServices.Settings("odp.transactions.scope"))); for (int i = 0; (i < log.Count); i++) { JToken entry = log[i]; string controller = ((string)(entry["controller"])); string view = ((string)(entry["view"])); ActionArgs executeArgs = entry["args"].ToObject <ActionArgs>(); if (executeArgs.Sequence.HasValue) { sequence = executeArgs.Sequence.Value; if ((transactionScope == "sequence") && (sequence != lastSequence && (i > 0))) { connection.Commit(); _commitResult.Sequence = lastSequence; connection.BeginTransaction(); } lastSequence = sequence; } ControllerConfiguration config = LoadConfig(executeArgs.Controller); ProcessArguments(config, executeArgs); ActionResult executeResult = ControllerFactory.CreateDataController().Execute(controller, view, executeArgs); if (executeResult.Errors.Count > 0) { index = i; _commitResult.Index = index; _commitResult.Errors = executeResult.Errors.ToArray(); break; } else { ProcessResult(config, executeResult); } } if (index == -1) { connection.Commit(); _commitResult.Sequence = sequence; } else { connection.Rollback(); _commitResult.Index = index; } } } } catch (Exception ex) { _commitResult.Errors = new string[] { ex.Message }; _commitResult.Index = 0; } return(_commitResult); }
public virtual bool RequiresRESTAuthentication(HttpRequest request, ControllerConfiguration config) { return UriRestConfig.RequiresAuthentication(request, config); }
public static bool IsAuthorized(HttpRequest request, ControllerConfiguration config) { if (request.AcceptTypes == null) return false; foreach (UriRestConfig urc in Enumerate(config)) if (urc.IsMatch(request)) { // verify HTTP method string httpMethod = urc["Method"]; if (!(String.IsNullOrEmpty(httpMethod))) { string[] methodList = Regex.Split(httpMethod, "(\\s*,\\s*)"); if (!(methodList.Contains(request.HttpMethod))) return false; } // verify user identity string users = urc["Users"]; if (!(String.IsNullOrEmpty(users)) && !((users == "?"))) { if (!(HttpContext.Current.User.Identity.IsAuthenticated)) return false; if (!((users == "*"))) { string[] userList = Regex.Split(users, "(\\s*,\\s*)"); if (!(userList.Contains(HttpContext.Current.User.Identity.Name))) return false; } } // verify user roles string roles = urc["Roles"]; if (!(String.IsNullOrEmpty(roles)) && !(DataControllerBase.UserIsInRole(roles))) return false; // verify SSL, Xml, and JSON constrains if (true.ToString().Equals(urc["Ssl"], StringComparison.OrdinalIgnoreCase) && !(request.IsSecureConnection)) return false; if (false.ToString().Equals(urc["Xml"], StringComparison.OrdinalIgnoreCase) && !(IsJSONRequest(request))) return false; if (false.ToString().Equals(urc["Json"], StringComparison.OrdinalIgnoreCase) && IsJSONRequest(request)) return false; return true; } return false; }
public static ControllerConfiguration CreateConfigurationInstance(Type t, string controller) { string configKey = ("DataController_" + controller); ControllerConfiguration config = ((ControllerConfiguration)(HttpContext.Current.Items[configKey])); if (config != null) return config; config = ((ControllerConfiguration)(HttpRuntime.Cache[configKey])); if (config == null) { Stream res = ControllerFactory.GetDataControllerStream(controller); bool allowCaching = (res == null); if (res == DefaultDataControllerStream) res = null; if (res == null) res = t.Assembly.GetManifestResourceStream(String.Format("MyCompany.Controllers.{0}.xml", controller)); if (res == null) res = t.Assembly.GetManifestResourceStream(String.Format("MyCompany.{0}.xml", controller)); if (res == null) { string controllerPath = Path.Combine(Path.Combine(HttpRuntime.AppDomainAppPath, "Controllers"), (controller + ".xml")); if (!(File.Exists(controllerPath))) throw new Exception(String.Format("Controller \'{0}\' does not exist.", controller)); config = new ControllerConfiguration(controllerPath); if (allowCaching) HttpRuntime.Cache.Insert(configKey, config, new CacheDependency(controllerPath)); } else { config = new ControllerConfiguration(res); if (allowCaching) HttpRuntime.Cache.Insert(configKey, config); } } bool requiresLocalization = config.RequiresLocalization; if (config.UsesVariables) config = config.Clone(); config = config.EnsureVitalElements(); if (config.PlugIn != null) config = config.PlugIn.Create(config); if (requiresLocalization) config = config.Localize(controller); if (config.RequiresVirtualization(controller)) config = config.Virtualize(controller); config.Complete(); HttpContext.Current.Items[configKey] = config; return config; }
public static bool RequiresAuthentication(HttpRequest request, ControllerConfiguration config) { foreach (UriRestConfig urc in Enumerate(config)) if (urc.IsMatch(request) && (urc["Users"] == "?")) return false; return true; }
protected virtual bool AuthorizeRequest(HttpRequest request, ControllerConfiguration config) { return UriRestConfig.IsAuthorized(request, config); }
protected XPathNavigator SelectActionGroup(ControllerConfiguration config, string actionGroupId) { return config.SelectSingleNode("/c:dataController/c:actions/c:actionGroup[@id=\'{0}\']", actionGroupId); }
public virtual ControllerConfiguration EnsureVitalElements() { // verify that the data controller has views and actions XPathNavigator root = SelectSingleNode("/c:dataController[c:views/c:view and c:actions/c:actionGroup]"); if (root != null) return this; // add missing configuration elements XmlDocument doc = new XmlDocument(); doc.LoadXml(_navigator.OuterXml); ControllerConfiguration config = new ControllerConfiguration(doc.CreateNavigator()); XPathNavigator fieldsNode = config.SelectSingleNode("/c:dataController/c:fields[not(c:field[@isPrimaryKey=\'true\'])]"); if (fieldsNode != null) fieldsNode.AppendChild("<field name=\"PrimaryKey\" type=\"Int32\" isPrimaryKey=\"true\" readOnly=\"true\"/>"); root = config.SelectSingleNode("/c:dataController"); EnsureChildNode(root, "views"); XPathNavigator viewsNode = config.SelectSingleNode("/c:dataController/c:views[not(c:view)]"); if (viewsNode != null) { StringBuilder sb = new StringBuilder("<view id=\"view1\" type=\"Form\" label=\"Form\"><categories><category id=\"c1\" newColumn" + "=\"true\"><dataFields>"); XPathNodeIterator fieldIterator = config.Select("/c:dataController/c:fields/c:field"); while (fieldIterator.MoveNext()) { string fieldName = fieldIterator.Current.GetAttribute("name", String.Empty); bool hidden = (fieldName == "PrimaryKey"); string length = fieldIterator.Current.GetAttribute("length", String.Empty); if (String.IsNullOrEmpty(length) && (((bool)(fieldIterator.Current.Evaluate("not(c:items/@style!=\'\')", _resolver))) == true)) if (fieldIterator.Current.GetAttribute("type", String.Empty) == "String") length = "50"; else length = "20"; sb.AppendFormat("<dataField fieldName=\"{0}\" hidden=\"{1}\"", fieldName, hidden.ToString().ToLower()); if (!(String.IsNullOrEmpty(length))) sb.AppendFormat(" columns=\"{0}\"", length); sb.Append(" />"); } sb.Append("</dataFields></category></categories></view>"); viewsNode.AppendChild(sb.ToString()); } EnsureChildNode(root, "actions"); XPathNavigator actionsNode = config.SelectSingleNode("/c:dataController/c:actions[not(c:actionGroup)]"); if (actionsNode != null) actionsNode.AppendChild(@"<actionGroup id=""ag1"" scope=""Form""> <action id=""a1"" commandName=""Confirm"" causesValidation=""true"" whenLastCommandName=""New"" /> <action id=""a2"" commandName=""Cancel"" whenLastCommandName=""New"" /> <action id=""a3"" commandName=""Confirm"" causesValidation=""true"" whenLastCommandName=""Edit"" /> <action id=""a4"" commandName=""Cancel"" whenLastCommandName=""Edit"" /> <action id=""a5"" commandName=""Edit"" causesValidation=""true"" /> </actionGroup>"); XPathNavigator plugIn = config.SelectSingleNode("/c:dataController/@plugIn"); if (plugIn != null) { plugIn.DeleteSelf(); config._plugIn = null; } return config; }
protected XPathNavigator SelectDataField(ControllerConfiguration config, string viewId, string fieldName) { return config.SelectSingleNode("/c:dataController/c:views/c:view[@id=\'{0}\']/.//c:dataField[@fieldName=\'{1}\' or @a" + "liasFieldName=\'{1}\']", viewId, fieldName); }
ControllerConfiguration IPlugIn.Create(ControllerConfiguration config) { if (config.Navigator.CanEdit) return config; XmlDocument document = new XmlDocument(); document.LoadXml(config.Navigator.OuterXml); return new ControllerConfiguration(document.CreateNavigator()); }
protected XPathNavigator SelectField(ControllerConfiguration config, string name) { return config.SelectSingleNode("/c:dataController/c:fields/c:field[@name=\'{0}\']", name); }
public void AssignContext(string controller, string view, ControllerConfiguration config) { _controller = controller; _view = view; string referrer = String.Empty; if (PageSize == 1000) { // we are processing a request to retrieve static lookup data XPathNavigator sortExpressionNode = config.SelectSingleNode("c:dataController/c:views/c:view[@id=\'{0}\']/@sortExpression", view); if ((sortExpressionNode != null) && !(String.IsNullOrEmpty(sortExpressionNode.Value))) this.SortExpression = sortExpressionNode.Value; } if ((HttpContext.Current != null) && (HttpContext.Current.Request.UrlReferrer != null)) referrer = HttpContext.Current.Request.UrlReferrer.AbsolutePath; this._contextKey = string.Format("{0}/{1}.{2}.{3}", referrer, controller, view, ContextKey); }
protected virtual void InternalEnsureTrackingFields(ViewPage page, ControllerConfiguration config) { bool hasCreatedByUserId = false; bool hasCreatedByUserName = false; bool hasCreatedOn = false; bool hasModifiedByUserId = false; bool hasModifiedByUserName = false; bool hasModifiedOn = false; // detect missing tracking fields foreach (DataField field in page.Fields) if (!(field.ReadOnly)) { if (IsCreatedByUserIdPattern(field.Name)) hasCreatedByUserId = true; if (IsCreatedByUserNamePattern(field.Name)) hasCreatedByUserName = true; if (IsCreatedOnPattern(field.Name)) hasCreatedOn = true; if (IsModifiedByUserIdPattern(field.Name)) hasModifiedByUserId = true; if (IsModifiedByUserNamePattern(field.Name)) hasModifiedByUserName = true; if (IsModifiedOnPattern(field.Name)) hasModifiedOn = true; } // Create DataField instances for missing tracking fields XPathNodeIterator fieldIterator = config.Select("/c:dataController/c:fields/c:field[not(@readOnly=\'true\')]"); while (fieldIterator.MoveNext()) { string fieldName = fieldIterator.Current.GetAttribute("name", String.Empty); // ensure that missing "created" data fields are declared if (!(hasCreatedByUserId) && IsCreatedByUserIdPattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasCreatedByUserId = true; } if (!(hasCreatedByUserName) && IsCreatedByUserNamePattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasCreatedByUserName = true; } if (!(hasCreatedOn) && IsCreatedOnPattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasCreatedOn = true; } // ensure that missing "modified" data fields are declared if (!(hasModifiedByUserId) && IsModifiedByUserIdPattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasModifiedByUserId = true; } if (!(hasModifiedByUserName) && IsModifiedByUserNamePattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasModifiedByUserName = true; } if (!(hasModifiedOn) && IsModifiedOnPattern(fieldName)) { page.Fields.Add(new DataField(fieldIterator.Current, config.Resolver)); hasModifiedOn = true; } } }