Exemple #1
0
 public bool PopulateStaticItems(DataField field, FieldValue[] contextValues)
 {
     if (field.SupportsStaticItems() && (String.IsNullOrEmpty(field.ContextFields) || ((contextValues != null) || (field.ItemsStyle == "CheckBoxList"))))
     {
         if (PopulatingStaticItems)
         {
             return(true);
         }
         PopulatingStaticItems = true;
         try
         {
             string[] filter = null;
             if (!(String.IsNullOrEmpty(field.ContextFields)))
             {
                 List <string> contextFilter = new List <string>();
                 Match         m             = Regex.Match(field.ContextFields, "(\\w+)=(.+?)($|,)");
                 while (m.Success)
                 {
                     Match vm = Regex.Match(m.Groups[2].Value, "^\'(.+?)\'$");
                     if (vm.Success)
                     {
                         contextFilter.Add(String.Format("{0}:={1}", m.Groups[1].Value, vm.Groups[1].Value));
                     }
                     else
                     if (contextValues != null)
                     {
                         foreach (FieldValue cv in contextValues)
                         {
                             if (cv.Name == m.Groups[2].Value)
                             {
                                 contextFilter.Add(String.Format("{0}:={1}", m.Groups[1].Value, cv.NewValue));
                                 break;
                             }
                         }
                     }
                     m = m.NextMatch();
                 }
                 filter = contextFilter.ToArray();
             }
             PageRequest request = new PageRequest(-1, 1000, field.ItemsDataTextField, filter);
             if (ActionArgs.Current != null)
             {
                 request.ExternalFilter = ActionArgs.Current.ExternalFilter;
             }
             ViewPage page = ControllerFactory.CreateDataController().GetPage(field.ItemsDataController, field.ItemsDataView, request);
             int      dataValueFieldIndex = page.Fields.IndexOf(page.FindField(field.ItemsDataValueField));
             if (dataValueFieldIndex == -1)
             {
                 foreach (DataField aField in page.Fields)
                 {
                     if (aField.IsPrimaryKey)
                     {
                         dataValueFieldIndex = page.Fields.IndexOf(aField);
                         break;
                     }
                 }
             }
             int dataTextFieldIndex = page.Fields.IndexOf(page.FindField(field.ItemsDataTextField));
             if (dataTextFieldIndex == -1)
             {
                 int i = 0;
                 while ((dataTextFieldIndex == -1) && (i < page.Fields.Count))
                 {
                     DataField f = page.Fields[i];
                     if (!(f.Hidden) && (f.Type == "String"))
                     {
                         dataTextFieldIndex = i;
                     }
                     i++;
                 }
                 if (dataTextFieldIndex == -1)
                 {
                     dataTextFieldIndex = 0;
                 }
             }
             List <int> fieldIndexes = new List <int>();
             fieldIndexes.Add(dataValueFieldIndex);
             fieldIndexes.Add(dataTextFieldIndex);
             if (!(String.IsNullOrEmpty(field.Copy)))
             {
                 Match m = Regex.Match(field.Copy, "(\\w+)=(\\w+)");
                 while (m.Success)
                 {
                     int copyFieldIndex = page.Fields.IndexOf(page.FindField(m.Groups[2].Value));
                     if (copyFieldIndex >= 0)
                     {
                         fieldIndexes.Add(copyFieldIndex);
                     }
                     m = m.NextMatch();
                 }
             }
             foreach (object[] row in page.Rows)
             {
                 object[] values = new object[fieldIndexes.Count];
                 for (int i = 0; (i < fieldIndexes.Count); i++)
                 {
                     int copyFieldIndex = fieldIndexes[i];
                     if (copyFieldIndex >= 0)
                     {
                         values[i] = row[copyFieldIndex];
                     }
                 }
                 field.Items.Add(values);
             }
             return(true);
         }
         finally
         {
             PopulatingStaticItems = false;
         }
     }
     return(false);
 }
        ActionResult IDataController.Execute(string controller, string view, ActionArgs args)
        {
            ActionResult result = new ActionResult();

            SelectView(controller, view);
            try
            {
                IActionHandler handler = _config.CreateActionHandler();
                if (_config.PlugIn != null)
                {
                    _config.PlugIn.PreProcessArguments(args, result, CreateViewPage());
                }
                if (args.SqlCommandType != CommandConfigurationType.None)
                {
                    using (DbConnection connection = CreateConnection())
                    {
                        ExecutePreActionCommands(args, result, connection);
                        if (handler != null)
                        {
                            handler.BeforeSqlAction(args, result);
                        }
                        else
                        {
                            CreateBusinessRules().ExecuteServerRules(args, result, ActionPhase.Before);
                        }
                        if ((result.Errors.Count == 0) && !(result.Canceled))
                        {
                            DbCommand command = CreateCommand(connection, args);
                            if ((args.SelectedValues != null) && (((args.LastCommandName == "BatchEdit") && (args.CommandName == "Update")) || ((args.CommandName == "Delete") && (args.SelectedValues.Length > 1))))
                            {
                                ViewPage page = CreateViewPage();
                                PopulatePageFields(page);
                                string originalCommandText = command.CommandText;
                                foreach (string sv in args.SelectedValues)
                                {
                                    string[] key      = sv.Split(',');
                                    int      keyIndex = 0;
                                    foreach (FieldValue v in args.Values)
                                    {
                                        DataField field = page.FindField(v.Name);
                                        if (field != null)
                                        {
                                            if (!(field.IsPrimaryKey))
                                            {
                                                v.Modified = true;
                                            }
                                            else
                                            if (v.Name == field.Name)
                                            {
                                                v.OldValue = key[keyIndex];
                                                v.Modified = false;
                                                keyIndex++;
                                            }
                                        }
                                    }
                                    ConfigureCommand(command, null, args.SqlCommandType, args.Values);
                                    result.RowsAffected = (result.RowsAffected + TransactionManager.ExecuteNonQuery(command));
                                    if (handler != null)
                                    {
                                        handler.AfterSqlAction(args, result);
                                    }
                                    else
                                    {
                                        CreateBusinessRules().ExecuteServerRules(args, result, ActionPhase.After);
                                    }
                                    command.CommandText = originalCommandText;
                                    command.Parameters.Clear();
                                    if (_config.PlugIn != null)
                                    {
                                        _config.PlugIn.ProcessArguments(args, result, page);
                                    }
                                    result.Canceled = false;
                                }
                            }
                            else
                            {
                                if (ConfigureCommand(command, null, args.SqlCommandType, args.Values))
                                {
                                    result.RowsAffected = TransactionManager.ExecuteNonQuery(args, result, CreateViewPage(), command);
                                    if (result.RowsAffected == 0)
                                    {
                                        result.RowNotFound = true;
                                        result.Errors.Add(Localizer.Replace("RecordChangedByAnotherUser", "The record has been changed by another user."));
                                    }
                                    else
                                    {
                                        ExecutePostActionCommands(args, result, connection);
                                    }
                                }
                                if (handler != null)
                                {
                                    handler.AfterSqlAction(args, result);
                                }
                                else
                                {
                                    CreateBusinessRules().ExecuteServerRules(args, result, ActionPhase.After);
                                }
                                if (_config.PlugIn != null)
                                {
                                    _config.PlugIn.ProcessArguments(args, result, CreateViewPage());
                                }
                            }
                        }
                    }
                }
                else
                if (args.CommandName.StartsWith("Export"))
                {
                    ExecuteDataExport(args, result);
                }
                else
                if (args.CommandName.Equals("PopulateDynamicLookups"))
                {
                    PopulateDynamicLookups(args, result);
                }
                else
                if (args.CommandName.Equals("ProcessImportFile"))
                {
                    ImportProcessor.Execute(args);
                }
                else
                if (args.CommandName.Equals("Execute"))
                {
                    using (DbConnection connection = CreateConnection())
                    {
                        DbCommand command = CreateCommand(connection, args);
                        TransactionManager.ExecuteNonQuery(command);
                    }
                }
                else
                if (handler != null)
                {
                    handler.ExecuteAction(args, result);
                    ((BusinessRules)(handler)).ProcessSpecialActions(args, result);
                }
                else
                {
                    CreateBusinessRules().ProcessSpecialActions(args, result);
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(System.Reflection.TargetInvocationException))
                {
                    ex = ex.InnerException;
                }
                HandleException(ex, args, result);
            }
            return(result);
        }
        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);
            }
        }
        ViewPage IDataController.GetPage(string controller, string view, PageRequest request)
        {
            SelectView(controller, view);
            request.AssignContext(controller, this._viewId);
            ViewPage page = new ViewPage(request);

            if (_config.PlugIn != null)
            {
                _config.PlugIn.PreProcessPageRequest(request, page);
            }
            _config.AssignDynamicExpressions(page);
            page.ApplyDataFilter(_config.CreateDataFilter(), request.Controller, request.View, request.LookupContextController, request.LookupContextView, request.LookupContextFieldName);
            BusinessRules rules = _config.CreateBusinessRules();

            _serverRules = rules;
            if (_serverRules == null)
            {
                _serverRules = CreateBusinessRules();
            }
            _serverRules.Page             = page;
            _serverRules.RequiresRowCount = (page.RequiresRowCount && !((request.Inserting || request.DoesNotRequireData)));
            if (rules != null)
            {
                rules.BeforeSelect(request);
            }
            else
            {
                _serverRules.ExecuteServerRules(request, ActionPhase.Before);
            }
            using (DbConnection connection = CreateConnection())
            {
                if (_serverRules.RequiresRowCount)
                {
                    DbCommand countCommand = CreateCommand(connection);
                    ConfigureCommand(countCommand, page, CommandConfigurationType.SelectCount, null);
                    if (YieldsSingleRow(countCommand))
                    {
                        page.TotalRowCount = 1;
                    }
                    else
                    {
                        page.TotalRowCount = Convert.ToInt32(countCommand.ExecuteScalar());
                    }
                    if (page.RequiresAggregates)
                    {
                        DbCommand aggregateCommand = CreateCommand(connection);
                        ConfigureCommand(aggregateCommand, page, CommandConfigurationType.SelectAggregates, null);
                        DbDataReader reader = aggregateCommand.ExecuteReader();
                        if (reader.Read())
                        {
                            object[] aggregates = new object[page.Fields.Count];
                            for (int i = 0; (i < aggregates.Length); i++)
                            {
                                DataField field = page.Fields[i];
                                if (field.Aggregate != DataFieldAggregate.None)
                                {
                                    object v = reader[field.Name];
                                    if (!(DBNull.Value.Equals(v)))
                                    {
                                        if (!(field.FormatOnClient) && !(String.IsNullOrEmpty(field.DataFormatString)))
                                        {
                                            v = String.Format(field.DataFormatString, v);
                                        }
                                        aggregates[i] = v;
                                    }
                                }
                            }
                            page.Aggregates = aggregates;
                        }
                        reader.Close();
                    }
                }
                if (page.RequiresMetaData)
                {
                    PopulatePageCategories(page);
                }
                SyncRequestedPage(request, page, connection);
                DbCommand selectCommand = CreateCommand(connection);
                ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null);
                if ((page.PageSize > 0) && !((request.Inserting || request.DoesNotRequireData)))
                {
                    EnsureSystemPageFields(request, page, selectCommand);
                    DbDataReader reader = null;
                    if (selectCommand == null)
                    {
                        reader = ExecuteVirtualReader(request, page);
                    }
                    else
                    {
                        reader = TransactionManager.ExecuteReader(request, page, selectCommand);
                    }
                    while (page.SkipNext())
                    {
                        reader.Read();
                    }
                    while (page.ReadNext() && reader.Read())
                    {
                        object[] values = new object[page.Fields.Count];
                        for (int i = 0; (i < values.Length); i++)
                        {
                            DataField field = page.Fields[i];
                            object    v     = reader[field.Name];
                            if (!(DBNull.Value.Equals(v)))
                            {
                                if (field.IsMirror)
                                {
                                    v = String.Format(field.DataFormatString, v);
                                }
                                else
                                if ((field.Type == "Guid") && (v.GetType() == typeof(byte[])))
                                {
                                    v = new Guid(((byte[])(v)));
                                }
                                else
                                {
                                    v = ConvertObjectToValue(v);
                                }
                                values[i] = v;
                            }
                            if (!(String.IsNullOrEmpty(field.SourceFields)))
                            {
                                values[i] = CreateValueFromSourceFields(field, reader);
                            }
                        }
                        page.Rows.Add(values);
                    }
                    reader.Close();
                }
            }
            if (_config.PlugIn != null)
            {
                _config.PlugIn.ProcessPageRequest(request, page);
            }
            if (request.Inserting)
            {
                page.NewRow = new object[page.Fields.Count];
            }
            if (request.Inserting)
            {
                if (_serverRules.SupportsCommand("Sql|Code", "New"))
                {
                    _serverRules.ExecuteServerRules(request, ActionPhase.Execute, "New", page.NewRow);
                }
            }
            else
            if (_serverRules.SupportsCommand("Sql|Code", "Select"))
            {
                foreach (object[] row in page.Rows)
                {
                    _serverRules.ExecuteServerRules(request, ActionPhase.Execute, "Select", row);
                }
            }
            if (rules != null)
            {
                IRowHandler rowHandler = rules;
                if (request.Inserting)
                {
                    if (rowHandler.SupportsNewRow(request))
                    {
                        rowHandler.NewRow(request, page, page.NewRow);
                    }
                }
                else
                if (rowHandler.SupportsPrepareRow(request))
                {
                    foreach (object[] row in page.Rows)
                    {
                        rowHandler.PrepareRow(request, page, row);
                    }
                }
                if (rules != null)
                {
                    rules.ProcessPageRequest(request, page);
                }
            }
            page = page.ToResult(_config, _view);
            if (rules != null)
            {
                rules.AfterSelect(request);
            }
            else
            {
                _serverRules.ExecuteServerRules(request, ActionPhase.After);
            }
            _serverRules.Result.Merge(page);
            return(page);
        }