Esempio n. 1
0
        public BusinessObjectParameters(params Object[] values)
        {
            string parameterMarker = null;

            for (int i = 0; (i < values.Length); i++)
            {
                object v = values[i];
                if (v is FieldValue)
                {
                    FieldValue fv = ((FieldValue)(v));
                    Add(fv.Name, fv.Value);
                }
                else
                {
                    if (String.IsNullOrEmpty(parameterMarker))
                    {
                        parameterMarker = SqlStatement.GetParameterMarker(String.Empty);
                    }
                    Add((parameterMarker
                         + ("p" + i.ToString())), v);
                }
            }
        }
Esempio n. 2
0
 public static string GenerateDataRecordPath(string controller, ViewPage page, FieldValue[] values, int rowIndex)
 {
     // Sample path:
     // [Documents]\Code OnTime\Projects\Web Site Factory\Annotations\App_Data\OrderDetails\10248,11
     // Sample URL parameter:
     // u|OrderDetails,_Annotation_AttachmentNew|10248|11
     string p = AnnotationPlugIn.AnnotationsPath;
     if (String.IsNullOrEmpty(controller))
     {
         string handlerInfo = HttpContext.Current.Request["AnnotationPlugIn"];
         Match m = Regex.Match(handlerInfo, "^((t|o|u)\\|){0,1}\\w+\\|(\\w+).+?\\|(.+)?$");
         if (m.Success)
         {
             p = Path.Combine(p, m.Groups[3].Value);
             p = Path.Combine(p, m.Groups[4].Value.Replace("|", ","));
         }
     }
     else
     {
         p = Path.Combine(p, controller);
         string keys = String.Empty;
         foreach (DataField field in page.Fields)
             if (field.IsPrimaryKey)
             {
                 string keyValue = null;
                 if (values == null)
                     keyValue = Convert.ToString(page.Rows[rowIndex][page.Fields.IndexOf(field)]);
                 else
                     foreach (FieldValue v in values)
                         if (v.Name == field.Name)
                         {
                             keyValue = Convert.ToString(v.Value);
                             break;
                         }
                 if (keys.Length > 0)
                     keys = (keys + ",");
                 keys = (keys + keyValue.Trim());
             }
         p = Path.Combine(p, keys);
     }
     return p;
 }
Esempio n. 3
0
 public override void ValidateFieldValue(FieldValue fv)
 {
 }
 protected virtual void ExecuteRule(string ruleId)
 {
     MethodInfo[] methods = GetType().GetMethods((BindingFlags.Public | (BindingFlags.NonPublic | BindingFlags.Instance)));
     foreach (MethodInfo method in methods)
     {
         object[] ruleBindings = method.GetCustomAttributes(typeof(RuleAttribute), true);
         foreach (RuleAttribute ra in ruleBindings)
         {
             if (ra.Id == ruleId)
             {
                 BlockRule(ruleId);
                 ParameterInfo[] parameters = method.GetParameters();
                 object[]        arguments  = new object[parameters.Length];
                 for (int i = 0; (i < parameters.Length); i++)
                 {
                     ParameterInfo p = parameters[i];
                     if ((parameters.Length == 1) && p.ParameterType.IsSubclassOf(typeof(BusinessRulesObjectModel)))
                     {
                         object self = p.ParameterType.Assembly.CreateInstance(p.ParameterType.FullName, true, BindingFlags.CreateInstance, null, new object[] {
                             this
                         }, System.Globalization.CultureInfo.CurrentCulture, null);
                         System.Reflection.FieldInfo[] fields = self.GetType().GetFields((BindingFlags.Instance | BindingFlags.NonPublic));
                         foreach (System.Reflection.FieldInfo fi in fields)
                         {
                             string fieldName = fi.Name.Substring("_".Length);
                             if (fieldName.Length == 1)
                             {
                                 fieldName = fieldName.ToUpper();
                             }
                             else
                             {
                                 fieldName = (char.ToUpper(fieldName[0]) + fieldName.Substring(1));
                             }
                             FieldValue v = SelectFieldValueObject(fieldName);
                             if (v != null)
                             {
                                 try
                                 {
                                     self.GetType().InvokeMember(fi.Name, (BindingFlags.SetField | (BindingFlags.Instance | BindingFlags.NonPublic)), null, self, new object[] {
                                         DataControllerBase.ConvertToType(fi.FieldType, v.Value)
                                     });
                                 }
                                 finally
                                 {
                                     // release resources here
                                 }
                             }
                         }
                         arguments[i] = self;
                     }
                     else
                     {
                         FieldValue v = SelectFieldValueObject(p.Name);
                         if (v != null)
                         {
                             if (p.ParameterType.Equals(typeof(FieldValue)))
                             {
                                 arguments[i] = v;
                             }
                             else
                             {
                                 try
                                 {
                                     arguments[i] = DataControllerBase.ConvertToType(p.ParameterType, v.Value);
                                 }
                                 catch (Exception)
                                 {
                                 }
                             }
                         }
                     }
                 }
                 method.Invoke(this, arguments);
             }
         }
     }
 }
        private bool InternalExecuteMethod(ActionArgs args, ActionResult result, ActionPhase phase, bool viewMatch, bool argumentMatch)
        {
            _arguments = args;
            _result    = result;
            bool success = false;

            MethodInfo[] methods = GetType().GetMethods((BindingFlags.Public | (BindingFlags.NonPublic | BindingFlags.Instance)));
            foreach (MethodInfo method in methods)
            {
                object[] filters = method.GetCustomAttributes(typeof(ControllerActionAttribute), true);
                foreach (ControllerActionAttribute action in filters)
                {
                    if (((action.Controller == args.Controller) || (!(String.IsNullOrEmpty(args.Controller)) && Regex.IsMatch(args.Controller, action.Controller))) && ((!(viewMatch) && String.IsNullOrEmpty(action.View)) || (action.View == args.View)))
                    {
                        if ((action.CommandName == args.CommandName) && ((!(argumentMatch) && String.IsNullOrEmpty(action.CommandArgument)) || (action.CommandArgument == args.CommandArgument)))
                        {
                            if (action.Phase == phase)
                            {
                                ParameterInfo[] parameters = method.GetParameters();
                                if ((parameters.Length == 2) && ((parameters[0].ParameterType == typeof(ActionArgs)) && (parameters[1].ParameterType == typeof(ActionResult))))
                                {
                                    method.Invoke(this, new object[] {
                                        args,
                                        result
                                    });
                                }
                                else
                                {
                                    object[] arguments = new object[parameters.Length];
                                    for (int i = 0; (i < parameters.Length); i++)
                                    {
                                        ParameterInfo p = parameters[i];
                                        FieldValue    v = SelectFieldValueObject(p.Name);
                                        if (v != null)
                                        {
                                            if (p.ParameterType.Equals(typeof(FieldValue)))
                                            {
                                                arguments[i] = v;
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    arguments[i] = DataControllerBase.ConvertToType(p.ParameterType, v.Value);
                                                }
                                                catch (Exception)
                                                {
                                                }
                                            }
                                        }
                                    }
                                    method.Invoke(this, arguments);
                                    success = true;
                                }
                            }
                        }
                    }
                }
            }
            return(success);
        }
Esempio n. 6
0
 protected virtual bool ConfigureCommand(DbCommand command, ViewPage page, CommandConfigurationType commandConfiguration, FieldValue[] values)
 {
     if (page == null)
         page = new ViewPage();
     PopulatePageFields(page);
     if (command == null)
         return true;
     if (command.CommandType == CommandType.Text)
     {
         Match statementMatch = SqlSelectRegex1.Match(command.CommandText);
         if (!(statementMatch.Success))
             statementMatch = SqlSelectRegex2.Match(command.CommandText);
         SelectClauseDictionary expressions = _expressions;
         if (expressions == null)
         {
             expressions = ParseSelectExpressions(statementMatch.Groups["Select"].Value);
             _expressions = expressions;
         }
         EnsurePageFields(page, expressions);
         string commandId = _view.GetAttribute("commandId", String.Empty);
         bool commandIsCustom = ((_config.SelectSingleNode("/c:dataController/c:commands/c:command[@id=\'{0}\' and @custom=\'true\']", commandId) != null) || page.RequiresResultSet(commandConfiguration));
         AddComputedExpressions(expressions, page, commandConfiguration, commandIsCustom);
         if (statementMatch.Success)
         {
             string fromClause = statementMatch.Groups["From"].Value;
             string whereClause = statementMatch.Groups["Where"].Value;
             string orderByClause = statementMatch.Groups["OrderBy"].Value;
             if (commandIsCustom)
             {
                 fromClause = String.Format("({0}) resultset__", command.CommandText);
                 whereClause = String.Empty;
                 orderByClause = String.Empty;
             }
             string tableName = null;
             if (!(commandConfiguration.ToString().StartsWith("Select")))
                 tableName = ((string)(_config.Evaluate("string(/c:dataController/c:commands/c:command[@id=\'{0}\']/@tableName)", commandId)));
             if (String.IsNullOrEmpty(tableName))
                 tableName = TableNameRegex.Match(fromClause).Groups["Table"].Value;
             if (commandConfiguration == CommandConfigurationType.Update)
                 return ConfigureCommandForUpdate(command, page, expressions, tableName, values);
             else
                 if (commandConfiguration == CommandConfigurationType.Insert)
                     return ConfigureCommandForInsert(command, page, expressions, tableName, values);
                 else
                     if (commandConfiguration == CommandConfigurationType.Delete)
                         return ConfigureCommandForDelete(command, page, expressions, tableName, values);
                     else
                     {
                         ConfigureCommandForSelect(command, page, expressions, fromClause, whereClause, orderByClause, commandConfiguration);
                         ProcessExpressionParameters(command, expressions);
                     }
         }
         else
             if ((commandConfiguration == CommandConfigurationType.Select) && YieldsSingleRow(command))
             {
                 StringBuilder sb = new StringBuilder();
                 sb.Append("select ");
                 AppendSelectExpressions(sb, page, expressions, true);
                 command.CommandText = sb.ToString();
             }
         return commandConfiguration != CommandConfigurationType.None;
     }
     return (command.CommandType == CommandType.StoredProcedure);
 }
Esempio n. 7
0
 private bool ConfigureCommandForUpdate(DbCommand command, ViewPage page, SelectClauseDictionary expressions, string tableName, FieldValue[] values)
 {
     StringBuilder sb = new StringBuilder();
     sb.AppendFormat("update {0} set ", tableName);
     bool firstField = true;
     foreach (FieldValue v in values)
     {
         DataField field = page.FindField(v.Name);
         if ((field != null) && v.Modified)
         {
             sb.AppendLine();
             if (firstField)
                 firstField = false;
             else
                 sb.Append(",");
             sb.AppendFormat(RemoveTableAliasFromExpression(expressions[v.Name]));
             if ((v.NewValue == null) && field.HasDefaultValue)
                 sb.Append(String.Format("={0}", field.DefaultValue));
             else
             {
                 sb.AppendFormat("={0}p{1}", _parameterMarker, command.Parameters.Count);
                 DbParameter parameter = command.CreateParameter();
                 parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                 AssignParameterValue(parameter, field.Type, v.NewValue);
                 command.Parameters.Add(parameter);
             }
         }
     }
     if (firstField)
         return false;
     AppendWhereExpressions(sb, command, page, expressions, values);
     command.CommandText = sb.ToString();
     return true;
 }
Esempio n. 8
0
 private bool ConfigureCommandForDelete(DbCommand command, ViewPage page, SelectClauseDictionary expressions, string tableName, FieldValue[] values)
 {
     StringBuilder sb = new StringBuilder();
     sb.AppendFormat("delete from {0}", tableName);
     AppendWhereExpressions(sb, command, page, expressions, values);
     command.CommandText = sb.ToString();
     return true;
 }
Esempio n. 9
0
 public override void ValidateFieldValue(FieldValue fv)
 {
 }
Esempio n. 10
0
        public int ExecuteAction(ActionArgs args, ActionResult result, ViewPage page)
        {
            DataTable t = GetTable(args.Controller, null);

            if (args.CommandName == "Insert")
            {
                DataRow r = t.NewRow();
                foreach (FieldValue v in args.Values)
                {
                    DataField f = page.FindField(v.Name);
                    if (f.IsPrimaryKey && f.ReadOnly)
                    {
                        object key = null;
                        if (f.Type == "Guid")
                        {
                            key = Guid.NewGuid();
                        }
                        else
                        if (!(PrimaryKeys.TryGetValue(args.Controller, out key)))
                        {
                            key = -1;
                            PrimaryKeys.Add(args.Controller, key);
                        }
                        else
                        {
                            key = (Convert.ToInt32(key) - 1);
                            PrimaryKeys[args.Controller] = key;
                        }
                        r[v.Name] = key;
                        result.Values.Add(new FieldValue(v.Name, key));
                        FieldValue fv = args.SelectFieldValueObject(v.Name);
                        fv.NewValue = key;
                        fv.Modified = true;
                    }
                    else
                    if (v.Modified)
                    {
                        if (v.NewValue == null)
                        {
                            r[v.Name] = DBNull.Value;
                        }
                        else
                        {
                            r[v.Name] = v.NewValue;
                        }
                    }
                }
                t.Rows.Add(r);
                return(1);
            }
            else
            {
                DataRow targetRow = null;
                foreach (DataRow r in t.Rows)
                {
                    bool matched = true;
                    foreach (DataField f in page.Fields)
                    {
                        if (f.IsPrimaryKey)
                        {
                            object kv  = r[f.Name];
                            object kv2 = args.SelectFieldValueObject(f.Name).OldValue;
                            if (((kv == null) || (kv2 == null)) || !((kv.ToString() == kv2.ToString())))
                            {
                                matched = false;
                                break;
                            }
                        }
                    }
                    if (matched)
                    {
                        targetRow = r;
                        break;
                    }
                }
                if (targetRow == null)
                {
                    return(0);
                }
                if (args.CommandName == "Delete")
                {
                    t.Rows.Remove(targetRow);
                }
                else
                {
                    foreach (FieldValue v in args.Values)
                    {
                        if (v.Modified)
                        {
                            if (v.NewValue == null)
                            {
                                targetRow[v.Name] = DBNull.Value;
                            }
                            else
                            {
                                targetRow[v.Name] = v.NewValue;
                            }
                        }
                    }
                }
                return(1);
            }
        }
 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();
     }
 }
Esempio n. 12
0
        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;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 13
0
        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;
                        }
                    }
                }
            }
        }
Esempio n. 14
0
 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();
 }
Esempio n. 15
0
 private void AppendWhereExpressions(StringBuilder sb, DbCommand command, ViewPage page, SelectClauseDictionary expressions, FieldValue[] values)
 {
     sb.AppendLine();
     sb.Append("where");
     bool firstField = true;
     foreach (FieldValue v in values)
     {
         DataField field = page.FindField(v.Name);
         if ((field != null) && field.IsPrimaryKey)
         {
             sb.AppendLine();
             if (firstField)
                 firstField = false;
             else
                 sb.Append("and ");
             sb.AppendFormat(RemoveTableAliasFromExpression(expressions[v.Name]));
             sb.AppendFormat("={0}p{1}", _parameterMarker, command.Parameters.Count);
             DbParameter parameter = command.CreateParameter();
             parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
             AssignParameterValue(parameter, field.Type, v.OldValue);
             command.Parameters.Add(parameter);
         }
     }
     bool ignorePrimaryKeyInWhere = false;
     if (firstField)
     {
         foreach (FieldValue fv in values)
             if (fv.Name == "_IgnorePrimaryKeyInWhere")
             {
                 ignorePrimaryKeyInWhere = true;
                 break;
             }
         // if the first field has not been processed then a primary key has not been provided
         if (!(ignorePrimaryKeyInWhere))
             throw new Exception("A primary key field value is not provided.");
     }
     if (ignorePrimaryKeyInWhere || _config.ConflictDetectionEnabled)
         foreach (FieldValue v in values)
         {
             DataField field = page.FindField(v.Name);
             if ((field != null) && (!((field.IsPrimaryKey || field.OnDemand)) && !(v.ReadOnly)))
             {
                 sb.AppendLine();
                 if (firstField)
                     firstField = false;
                 else
                     sb.Append("and ");
                 sb.Append(RemoveTableAliasFromExpression(expressions[v.Name]));
                 if (v.OldValue == null)
                     sb.Append(" is null");
                 else
                 {
                     sb.AppendFormat("={0}p{1}", _parameterMarker, command.Parameters.Count);
                     DbParameter parameter = command.CreateParameter();
                     parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                     AssignParameterValue(parameter, field.Type, v.OldValue);
                     command.Parameters.Add(parameter);
                 }
             }
         }
     sb.AppendLine();
 }
Esempio n. 16
0
 protected virtual void UpdateUser(Guid userId, FieldValue email, FieldValue isApproved, FieldValue isLockedOut, FieldValue comment, FieldValue roles)
 {
     PreventDefault();
     MembershipUser user = Membership.GetUser(userId);
     // update user information
     if (email.Modified)
     {
         user.Email = Convert.ToString(email.Value);
         Membership.UpdateUser(user);
     }
     if (isApproved.Modified)
     {
         user.IsApproved = Convert.ToBoolean(isApproved.Value);
         Membership.UpdateUser(user);
     }
     if (isLockedOut.Modified)
     {
         if (Convert.ToBoolean(isLockedOut.Value))
         {
             Result.Focus("IsLockedOut", Localize("UserCannotBeLockedOut", "User cannot be locked out. If you want to prevent this user from being able to lo" +
                         "gin then simply mark user as \'not-approved\'."));
             throw new Exception(Localize("ErrorSavingUser", "Error saving user account."));
         }
         user.UnlockUser();
     }
     if (comment.Modified)
     {
         user.Comment = Convert.ToString(comment.Value);
         Membership.UpdateUser(user);
     }
     if (roles.Modified)
     {
         string[] newRoles = Convert.ToString(roles.Value).Split(',');
         string[] oldRoles = System.Web.Security.Roles.GetRolesForUser(user.UserName);
         foreach (string role in oldRoles)
             if (!(String.IsNullOrEmpty(role)) && (Array.IndexOf(newRoles, role) == -1))
                 System.Web.Security.Roles.RemoveUserFromRole(user.UserName, role);
         foreach (string role in newRoles)
             if (!(String.IsNullOrEmpty(role)) && (Array.IndexOf(oldRoles, role) == -1))
                 System.Web.Security.Roles.AddUserToRole(user.UserName, role);
     }
 }