protected virtual void AppendDeepFilter(string hint, ViewPage page, DbCommand command, StringBuilder sb, string filter)
 {
     string[] hintInfo = hint.Split(new char[] {
                 '.'});
     int index = filter.IndexOf(":");
     string fieldData = filter.Substring((index + 1));
     for (int i = 0; (i < NegativeFilterOperations.Length); i++)
     {
         string negativeOperation = NegativeFilterOperations[i];
         if (fieldData.StartsWith(negativeOperation))
         {
             sb.Append("not ");
             filter = (filter.Substring(0, (index + 1))
                         + (ReverseNegativeFilterOperations[i] + filter.Substring((index
                             + (1 + negativeOperation.Length)))));
             break;
         }
     }
     sb.Append("exists(");
     PageRequest r = new PageRequest();
     r.Controller = hintInfo[0];
     r.View = hintInfo[1];
     r.Filter = new string[] {
             filter};
     DataControllerBase controller = ((DataControllerBase)(ControllerFactory.CreateDataController()));
     foreach (DataField field in page.Fields)
         if (field.IsPrimaryKey)
         {
             r.InnerJoinPrimaryKey = ("resultset__." + field.Name);
             r.InnerJoinForeignKey = hintInfo[2];
             break;
         }
     controller.ConfigureSelectExistingCommand(r, command, sb);
     sb.Append(")");
 }
Exemple #2
0
 /// <summary>
 /// Generates a report using the default or custom report template with optional sort expression and filter applied to the dataset.
 /// </summary>
 /// <param name="args">A collection of parameters that control the report generation.</param>
 /// <returns>A binary array representing the report data.</returns>
 public static byte[] Execute(ReportArgs args)
 {
     Report reportHandler = new Report();
     Stream output = new MemoryStream();
     reportHandler.OutputStream = output;
     reportHandler.Arguments = args;
     PageRequest request = new PageRequest();
     reportHandler.Request = request;
     request.Controller = args.Controller;
     request.View = args.View;
     request.SortExpression = args.SortExpression;
     if (args.Filter != null)
     {
         DataViewExtender dve = new DataViewExtender();
         dve.AssignStartupFilter(args.Filter);
         request.Filter = ((List<string>)(dve.Properties["StartupFilter"])).ToArray();
     }
     ((IHttpHandler)(reportHandler)).ProcessRequest(HttpContext.Current);
     // return report data
     output.Position = 0;
     byte[] data = new byte[output.Length];
     output.Read(data, 0, data.Length);
     return data;
 }
Exemple #3
0
 protected virtual DbCommand CreateCommand(DbConnection connection, ActionArgs args)
 {
     string commandId = _view.GetAttribute("commandId", String.Empty);
     XPathNavigator commandNav = _config.SelectSingleNode("/c:dataController/c:commands/c:command[@id=\'{0}\']", commandId);
     if ((args != null) && !(String.IsNullOrEmpty(args.CommandArgument)))
     {
         XPathNavigator commandNav2 = _config.SelectSingleNode("/c:dataController/c:commands/c:command[@id=\'{0}\']", args.CommandArgument);
         if (commandNav2 != null)
             commandNav = commandNav2;
     }
     if (commandNav == null)
         return null;
     DbCommand command = SqlStatement.CreateCommand(connection);
     if (SinglePhaseTransactionScope.Current != null)
         SinglePhaseTransactionScope.Current.Enlist(command);
     string theCommandType = commandNav.GetAttribute("type", string.Empty);
     if (!(String.IsNullOrEmpty(theCommandType)))
         command.CommandType = ((CommandType)(TypeDescriptor.GetConverter(typeof(CommandType)).ConvertFromString(theCommandType)));
     command.CommandText = ((string)(commandNav.Evaluate("string(c:text)", Resolver)));
     if (String.IsNullOrEmpty(command.CommandText))
         command.CommandText = commandNav.InnerXml;
     IActionHandler handler = _config.CreateActionHandler();
     XPathNodeIterator parameterIterator = commandNav.Select("c:parameters/c:parameter", Resolver);
     SortedDictionary<string, string> missingFields = null;
     while (parameterIterator.MoveNext())
     {
         DbParameter parameter = command.CreateParameter();
         parameter.ParameterName = parameterIterator.Current.GetAttribute("name", String.Empty);
         string s = parameterIterator.Current.GetAttribute("type", String.Empty);
         if (!(String.IsNullOrEmpty(s)))
             parameter.DbType = ((DbType)(TypeDescriptor.GetConverter(typeof(DbType)).ConvertFromString(s)));
         s = parameterIterator.Current.GetAttribute("direction", String.Empty);
         if (!(String.IsNullOrEmpty(s)))
             parameter.Direction = ((ParameterDirection)(TypeDescriptor.GetConverter(typeof(ParameterDirection)).ConvertFromString(s)));
         command.Parameters.Add(parameter);
         s = parameterIterator.Current.GetAttribute("defaultValue", String.Empty);
         if (!(String.IsNullOrEmpty(s)))
             parameter.Value = s;
         s = parameterIterator.Current.GetAttribute("fieldName", String.Empty);
         if ((args != null) && !(String.IsNullOrEmpty(s)))
         {
             FieldValue v = args.SelectFieldValueObject(s);
             if (v != null)
             {
                 s = parameterIterator.Current.GetAttribute("fieldValue", String.Empty);
                 if (s == "Old")
                     parameter.Value = v.OldValue;
                 else
                     if (s == "New")
                         parameter.Value = v.NewValue;
                     else
                         parameter.Value = v.Value;
             }
             else
             {
                 if (missingFields == null)
                     missingFields = new SortedDictionary<string, string>();
                 missingFields.Add(parameter.ParameterName, s);
             }
         }
         s = parameterIterator.Current.GetAttribute("propertyName", String.Empty);
         if (!(String.IsNullOrEmpty(s)) && (handler != null))
         {
             object result = handler.GetType().InvokeMember(s, (System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.GetField), null, handler, new object[0]);
             parameter.Value = result;
         }
         if (parameter.Value == null)
             parameter.Value = DBNull.Value;
     }
     if (missingFields != null)
     {
         bool retrieveMissingValues = true;
         List<string> filter = new List<string>();
         ViewPage page = CreateViewPage();
         foreach (DataField field in page.Fields)
             if (field.IsPrimaryKey)
             {
                 FieldValue v = args.SelectFieldValueObject(field.Name);
                 if (v == null)
                 {
                     retrieveMissingValues = false;
                     break;
                 }
                 else
                     filter.Add(String.Format("{0}:={1}", v.Name, v.Value));
             }
         if (retrieveMissingValues)
         {
             string editView = ((string)(_config.Evaluate("string(//c:view[@type=\'Form\']/@id)")));
             if (!(String.IsNullOrEmpty(editView)))
             {
                 PageRequest request = new PageRequest(0, 1, null, filter.ToArray());
                 request.RequiresMetaData = true;
                 page = ControllerFactory.CreateDataController().GetPage(args.Controller, editView, request);
                 if (page.Rows.Count > 0)
                     foreach (string parameterName in missingFields.Keys)
                     {
                         int index = 0;
                         string fieldName = missingFields[parameterName];
                         foreach (DataField field in page.Fields)
                         {
                             if (field.Name.Equals(fieldName))
                             {
                                 object v = page.Rows[0][index];
                                 if (v != null)
                                     command.Parameters[parameterName].Value = v;
                             }
                             index++;
                         }
                     }
             }
         }
     }
     return command;
 }
Exemple #4
0
 public static string LookupText(string controllerName, string filterExpression, string fieldNames)
 {
     string[] dataTextFields = fieldNames.Split(',');
     PageRequest request = new PageRequest(-1, 1, null, new string[] {
                 filterExpression});
     ViewPage page = ControllerFactory.CreateDataController().GetPage(controllerName, String.Empty, request);
     string result = String.Empty;
     if (page.Rows.Count > 0)
         for (int i = 0; (i < page.Fields.Count); i++)
         {
             DataField field = page.Fields[i];
             if (Array.IndexOf(dataTextFields, field.Name) >= 0)
             {
                 if (result.Length > 0)
                     result = (result + "; ");
                 result = (result + Convert.ToString(page.Rows[0][i]));
             }
         }
     return result;
 }
 void IPlugIn.PreProcessPageRequest(PageRequest request, ViewPage page)
 {
     XPathNavigator view = _config.SelectSingleNode("//c:view[@id=\'{0}\' and @type=\'Form\']/c:categories", request.View);
     if ((view != null) && ((request.PageSize > 0) && (!(request.Inserting) && (_config.SelectSingleNode("/c:dataController/c:fields/c:field[@name=\'_Annotation_NoteNew\']") == null))))
     {
         _requireProcessing = true;
         string ns = ControllerConfiguration.Namespace;
         List<DynamicExpression> expressions = new List<DynamicExpression>(_config.Expressions);
         // create NewXXX fields under "fields" node
         StringBuilder sb = new StringBuilder();
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.ConformanceLevel = ConformanceLevel.Fragment;
         XmlWriter writer = XmlWriter.Create(sb, settings);
         // NoteNew field
         writer.WriteStartElement("field", ns);
         writer.WriteAttributeString("name", "_Annotation_NoteNew");
         writer.WriteAttributeString("type", "String");
         writer.WriteAttributeString("allowSorting", "false");
         writer.WriteAttributeString("allowQBE", "false");
         writer.WriteAttributeString("label", Localizer.Replace("AnnotationNoteNewFieldLabel", "Notes"));
         writer.WriteAttributeString("computed", "true");
         writer.WriteElementString("formula", ns, "null");
         writer.WriteEndElement();
         DynamicExpression de = new DynamicExpression();
         de.Target = "_Annotation_NoteNew";
         de.Scope = DynamicExpressionScope.DataFieldVisibility;
         de.Type = DynamicExpressionType.ClientScript;
         de.Test = "this.get_isEditing()";
         de.ViewId = request.View;
         expressions.Add(de);
         // AttachmentNew field
         writer.WriteStartElement("field", ns);
         writer.WriteAttributeString("name", "_Annotation_AttachmentNew");
         writer.WriteAttributeString("type", "Byte[]");
         writer.WriteAttributeString("onDemand", "true");
         writer.WriteAttributeString("sourceFields", this.KeyFields);
         writer.WriteAttributeString("onDemandHandler", "AnnotationPlugIn");
         writer.WriteAttributeString("allowQBE", "false");
         writer.WriteAttributeString("allowSorting", "false");
         writer.WriteAttributeString("label", Localizer.Replace("AnnotationAttachmentNewFieldLabel", "Attachment"));
         writer.WriteAttributeString("computed", "true");
         writer.WriteElementString("formula", ns, "null");
         writer.WriteEndElement();
         writer.Close();
         this.Fields.AppendChild(sb.ToString());
         DynamicExpression ade = new DynamicExpression();
         ade.Target = "_Annotation_AttachmentNew";
         ade.Scope = DynamicExpressionScope.DataFieldVisibility;
         ade.Type = DynamicExpressionType.ClientScript;
         ade.Test = "this.get_isEditing()";
         ade.ViewId = request.View;
         expressions.Add(ade);
         // create NewXXX data fields under "view/dataFields" node
         sb = new StringBuilder();
         writer = XmlWriter.Create(sb);
         writer.WriteStartElement("category", ns);
         writer.WriteAttributeString("id", "Annotations");
         writer.WriteAttributeString("headerText", Localizer.Replace("AnnotationCategoryHeaderText", "Notes and Attachments"));
         writer.WriteElementString("description", ns, Localizer.Replace("AnnotationCategoryDescription", "Enter optional notes and attach files."));
         writer.WriteStartElement("dataFields", ns);
         // _Annotation_NoteNew dataField
         writer.WriteStartElement("dataField", ns);
         writer.WriteAttributeString("fieldName", "_Annotation_NoteNew");
         writer.WriteAttributeString("columns", "50");
         writer.WriteAttributeString("rows", "7");
         writer.WriteEndElement();
         // _Annotation_AttachmentNew
         writer.WriteStartElement("dataField", ns);
         writer.WriteAttributeString("fieldName", "_Annotation_AttachmentNew");
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.Close();
         view.AppendChild(sb.ToString());
         _retrieveAnnotations = !(request.Inserting);
         _config.Expressions = expressions.ToArray();
     }
 }
Exemple #6
0
 protected virtual void SyncRequestedPage(PageRequest request, ViewPage page, DbConnection connection)
 {
     if (((request.SyncKey == null) || (request.SyncKey.Length == 0)) || (page.PageSize < 0))
         return;
     List<DataField> keyFields = new List<DataField>();
     foreach (DataField field in page.Fields)
         if (field.IsPrimaryKey)
             keyFields.Add(field);
     if ((keyFields.Count > 0) && (keyFields.Count == request.SyncKey.Length))
     {
         DbCommand syncCommand = CreateCommand(connection);
         ConfigureCommand(syncCommand, page, CommandConfigurationType.Sync, null);
         bool useSkip = (_serverRules.EnableResultSet || SupportsSkipInSelect(syncCommand));
         if (!(useSkip))
             for (int i = 0; (i < keyFields.Count); i++)
             {
                 DataField field = keyFields[i];
                 DbParameter p = syncCommand.CreateParameter();
                 p.ParameterName = String.Format("{0}PrimaryKey_{1}", _parameterMarker, field.Name);
                 AssignParameterValue(p, field.Type, request.SyncKey[i]);
                 syncCommand.Parameters.Add(p);
             }
         DbDataReader reader;
         if (_serverRules.EnableResultSet)
             reader = ExecuteResultSetReader(page);
         else
             reader = syncCommand.ExecuteReader();
         if (!(useSkip))
         {
             if (reader.Read())
             {
                 long rowIndex = Convert.ToInt64(reader[0]);
                 page.PageIndex = Convert.ToInt32(Math.Floor((Convert.ToDouble((rowIndex - 1)) / Convert.ToDouble(page.PageSize))));
                 page.PageOffset = 0;
             }
         }
         else
         {
             long rowIndex = 1;
             List<int> keyFieldIndexes = new List<int>();
             foreach (DataField pkField in keyFields)
                 keyFieldIndexes.Add(reader.GetOrdinal(pkField.Name));
             while (reader.Read())
             {
                 int matchCount = 0;
                 foreach (int primaryKeyFieldIndex in keyFieldIndexes)
                     if (Convert.ToString(reader[primaryKeyFieldIndex]) == Convert.ToString(request.SyncKey[matchCount]))
                         matchCount++;
                     else
                         break;
                 if (matchCount == keyFieldIndexes.Count)
                 {
                     page.PageIndex = Convert.ToInt32(Math.Floor((Convert.ToDouble((rowIndex - 1)) / Convert.ToDouble(page.PageSize))));
                     page.PageOffset = 0;
                     page.ResetSkipCount(false);
                     break;
                 }
                 else
                     rowIndex++;
             }
         }
         reader.Close();
     }
 }
Exemple #7
0
 protected virtual DbDataReader ExecuteVirtualReader(PageRequest request, ViewPage page)
 {
     DataTable table = new DataTable();
     foreach (DataField field in page.Fields)
         table.Columns.Add(field.Name, typeof(int));
     DataRow r = table.NewRow();
     if (page.ContainsField("PrimaryKey"))
         r["PrimaryKey"] = 1;
     table.Rows.Add(r);
     return new DataTableReader(table);
 }
Exemple #8
0
 DbDataReader IDataEngine.ExecuteReader(PageRequest request)
 {
     _viewPage = new ViewPage(request);
     if (_config == null)
     {
         _config = CreateConfiguration(request.Controller);
         SelectView(request.Controller, request.View);
     }
     _viewPage.ApplyDataFilter(_config.CreateDataFilter(), request.Controller, request.View, null, null, null);
     InitBusinessRules(request, _viewPage);
     DbConnection connection = CreateConnection();
     DbCommand selectCommand = CreateCommand(connection);
     ConfigureCommand(selectCommand, _viewPage, CommandConfigurationType.Select, null);
     return selectCommand.ExecuteReader(CommandBehavior.CloseConnection);
 }
Exemple #9
0
 protected virtual void InternalProcess(ViewPage page, PageRequest request)
 {
     int index = 0;
     foreach (DataField field in page.Fields)
     {
         if (!(field.ReadOnly))
             if (IsCreatedByUserIdPattern(field.Name) || IsModifiedByUserIdPattern(field.Name))
             {
                 field.TextMode = TextInputMode.Static;
                 field.Hidden = true;
                 if (IsNewRow(page, request) && (page.NewRow[index] == null))
                     page.NewRow[index] = UserId;
             }
             else
                 if (IsCreatedByUserNamePattern(field.Name) || IsModifiedByUserNamePattern(field.Name))
                 {
                     field.TextMode = TextInputMode.Static;
                     if (!(String.IsNullOrEmpty(Email)) && String.IsNullOrEmpty(field.HyperlinkFormatString))
                         field.HyperlinkFormatString = String.Format("mailto:{0}", Email);
                     if (IsNewRow(page, request) && (page.NewRow[index] == null))
                         page.NewRow[index] = UserName;
                 }
                 else
                     if (IsCreatedOnPattern(field.Name) || IsModifiedOnPattern(field.Name))
                     {
                         field.TextMode = TextInputMode.Static;
                         field.DataFormatString = DateTimeFormatString;
                         if (IsNewRow(page, request) && (page.NewRow[index] == null))
                             page.NewRow[index] = DateTime.Now;
                     }
         index++;
     }
 }
 protected virtual void ConfigureSelectExistingCommand(PageRequest request, DbCommand command, StringBuilder sb)
 {
     string controller = request.Controller;
     string view = request.View;
     SelectView(controller, view);
     request.AssignContext(controller, this._viewId, _config);
     ViewPage page = new ViewPage(request);
     if (_config.PlugIn != null)
         _config.PlugIn.PreProcessPageRequest(request, page);
     _config.AssignDynamicExpressions(page);
     InitBusinessRules(request, page);
     using (DbConnection connection = CreateConnection())
     {
         DbCommand selectCommand = CreateCommand(connection);
         if ((selectCommand == null) && _serverRules.EnableResultSet)
         {
             // it is not possible to "deep" search in this controller
             sb.AppendLine("select 1");
             return;
         }
         ConfigureCommand(selectCommand, page, CommandConfigurationType.SelectExisting, null);
     }
     string commandText = _currentCommand.CommandText;
     int parameterIndex = (_currentCommand.Parameters.Count - 1);
     while (parameterIndex >= 0)
     {
         DbParameter p = _currentCommand.Parameters[parameterIndex];
         string newParameterName = (_parameterMarker
                     + ("cp" + command.Parameters.Count.ToString()));
         commandText = commandText.Replace(p.ParameterName, newParameterName);
         p.ParameterName = newParameterName;
         _currentCommand.Parameters.RemoveAt(parameterIndex);
         command.Parameters.Add(p);
         parameterIndex = (parameterIndex - 1);
     }
     int resultSetIndex = commandText.IndexOf("resultset__");
     int resultSetLastIndex = commandText.LastIndexOf("resultset__");
     if (resultSetIndex < resultSetLastIndex)
         commandText = (commandText.Substring(0, (resultSetIndex + 9))
                     + ("2" + commandText.Substring((resultSetIndex + 9))));
     sb.AppendLine(commandText);
 }
Exemple #11
0
 private static bool RowIsMatched(PageRequest request, ViewPage page, DataRow row)
 {
     foreach (string f in request.Filter)
     {
         Match m = Regex.Match(f, "^(?\'FieldName\'\\w+)\\:(?\'Operation\'=)(?\'Value\'.+)$");
         if (m.Success)
         {
             string fieldName = m.Groups["FieldName"].Value;
             if (page.ContainsField(fieldName))
             {
                 string fieldValue = m.Groups["Value"].Value;
                 if (fieldValue == "null")
                     fieldValue = String.Empty;
                 object fv = row[fieldName];
                 if (!((Convert.ToString(fv) == fieldValue)))
                     return false;
             }
         }
     }
     return true;
 }
Exemple #12
0
 public static DbDataReader ExecuteReader(PageRequest request, ViewPage page, DbCommand command)
 {
     TransactionManager tm = Create(request.Transaction);
     if (tm == null)
         return command.ExecuteReader();
     DataTable t = tm.GetTable(request.Controller, command);
     t.DefaultView.Sort = request.SortExpression;
     DataTable t2 = t.Clone();
     int rowsToSkip = (page.PageIndex * page.PageSize);
     foreach (DataRowView r in t.DefaultView)
         if (RowIsMatched(request, page, r.Row))
             if (rowsToSkip > 0)
                 rowsToSkip++;
             else
             {
                 DataRow r2 = t2.NewRow();
                 foreach (DataColumn c in t.Columns)
                     r2[c.ColumnName] = r[c.ColumnName];
                 t2.Rows.Add(r2);
                 if (t2.Rows.Count == page.PageSize)
                     break;
             }
     if (page.RequiresRowCount)
     {
         int totalRowCount = 0;
         foreach (DataRowView r in t.DefaultView)
             if (RowIsMatched(request, page, r.Row))
                 totalRowCount++;
         page.TotalRowCount = totalRowCount;
     }
     return new DataTableReader(t2);
 }
Exemple #13
0
 protected virtual string FormatFileName(HttpContext context, PageRequest request, string extension)
 {
     return null;
 }
Exemple #14
0
 public virtual ViewPage[] GetPageList(PageRequest[] requests)
 {
     List<ViewPage> result = new List<ViewPage>();
     foreach (PageRequest r in requests)
         result.Add(((IDataController)(this)).GetPage(r.Controller, r.View, r));
     return result.ToArray();
 }
Exemple #15
0
 protected virtual bool IsNewRow(ViewPage page, PageRequest request)
 {
     if (request.Inserting && (page.NewRow == null))
         page.NewRow = new object[page.Fields.Count];
     return request.Inserting;
 }
Exemple #16
0
 ViewPage IDataController.GetPage(string controller, string view, PageRequest request)
 {
     SelectView(controller, view);
     request.AssignContext(controller, this._viewId, _config);
     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 = InitBusinessRules(request, page);
     using (DbConnection connection = CreateConnection())
     {
         if (_serverRules.RequiresRowCount)
         {
             DbCommand countCommand = CreateCommand(connection);
             ConfigureCommand(countCommand, page, CommandConfigurationType.SelectCount, null);
             if (_serverRules.EnableResultSet)
                 page.TotalRowCount = _serverRules.ResultSetSize;
             else
                 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();
             }
         }
         DbCommand selectCommand = CreateCommand(connection);
         if ((selectCommand == null) && _serverRules.EnableResultSet)
         {
             PopulatePageFields(page);
             EnsurePageFields(page, null);
         }
         if (page.RequiresMetaData)
             PopulatePageCategories(page);
         SyncRequestedPage(request, page, connection);
         ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null);
         if ((page.PageSize > 0) && !((request.Inserting || request.DoesNotRequireData)))
         {
             EnsureSystemPageFields(request, page, selectCommand);
             DbDataReader reader = ExecuteResultSetReader(page);
             if (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);
                 }
                 if (page.RequiresPivot)
                     page.AddPivotValues(values);
                 else
                     page.Rows.Add(values);
             }
             reader.Close();
         }
         if (request.RequiresFirstLetters && this._viewType != "Form")
             if (!(page.RequiresRowCount))
                 page.FirstLetters = String.Empty;
             else
             {
                 DbCommand firstLettersCommand = CreateCommand(connection);
                 string[] oldFilter = page.Filter;
                 ConfigureCommand(firstLettersCommand, page, CommandConfigurationType.SelectFirstLetters, null);
                 page.Filter = oldFilter;
                 if (!(String.IsNullOrEmpty(page.FirstLetters)))
                 {
                     DbDataReader reader = firstLettersCommand.ExecuteReader();
                     StringBuilder firstLetters = new StringBuilder(page.FirstLetters);
                     while (reader.Read())
                     {
                         firstLetters.Append(",");
                         string letter = Convert.ToString(reader[0]);
                         if (!(String.IsNullOrEmpty(letter)))
                             firstLetters.Append(letter);
                     }
                     reader.Close();
                     page.FirstLetters = firstLetters.ToString();
                 }
             }
     }
     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);
         rules.ProcessPageRequest(request, page);
         if (rules.CompleteConfiguration())
             ResetViewPage(page);
     }
     page = page.ToResult(_config, _view);
     if (rules != null)
         rules.AfterSelect(request);
     else
         _serverRules.ExecuteServerRules(request, ActionPhase.After);
     _serverRules.Result.Merge(page);
     return page;
 }
Exemple #17
0
 public static void Process(ViewPage page, PageRequest request)
 {
     EventTracker tracker = new EventTracker();
     tracker.InternalProcess(page, request);
 }
Exemple #18
0
 protected virtual void EnsureSystemPageFields(PageRequest request, ViewPage page, DbCommand command)
 {
     if (!(RequiresHierarchy(page)))
         return;
     bool requiresHierarchyOrganization = false;
     foreach (DataField field in page.Fields)
         if (field.IsTagged("hierarchy-parent"))
             requiresHierarchyOrganization = true;
         else
             if (field.IsTagged("hierarchy-organization"))
             {
                 requiresHierarchyOrganization = false;
                 break;
             }
     if (requiresHierarchyOrganization)
     {
         DataField field = new DataField();
         field.Name = HierarchyOrganizationFieldName;
         field.Type = "String";
         field.Tag = "hierarchy-organization";
         field.Len = 255;
         field.Columns = 20;
         field.Hidden = true;
         field.ReadOnly = true;
         page.Fields.Add(field);
     }
 }
 protected virtual void ExecuteHttpGetRequest(HttpRequest request, HttpResponse response, Stream output, bool json, string controllerName, string view, List<string> filter, bool keyIsAvailable)
 {
     // prepare a page request
     int pageSize;
     int.TryParse(request.QueryString["_pageSize"], out pageSize);
     if (pageSize == 0)
         pageSize = 100;
     int pageIndex;
     int.TryParse(request.QueryString["_pageIndex"], out pageIndex);
     PageRequest r = new PageRequest();
     r.Controller = controllerName;
     r.View = view;
     r.RequiresMetaData = true;
     r.PageSize = pageSize;
     r.PageIndex = pageIndex;
     r.Filter = filter.ToArray();
     r.RequiresRowCount = ((pageIndex == 0) && !(keyIsAvailable));
     r.SortExpression = request.QueryString["_sortExpression"];
     // request the data
     IDataController controllerInstance = ControllerFactory.CreateDataController();
     ViewPage page = controllerInstance.GetPage(r.Controller, r.View, r);
     if (keyIsAvailable && (page.Rows.Count == 0))
     {
         response.StatusCode = 404;
         return;
     }
     // stream out the data
     XmlWriter writer = null;
     StreamWriter sw = null;
     if (json)
     {
         sw = CreateStreamWriter(request, response, output);
         BeginResponsePadding(request, sw);
         if (!(keyIsAvailable))
         {
             sw.Write("{");
             if (r.RequiresRowCount)
                 sw.Write("\"totalRowCount\":{0},", page.TotalRowCount);
             sw.Write("\"pageSize\":{0},\"pageIndex\":{1},\"rowCount\":{2},", page.PageSize, page.PageIndex, page.Rows.Count);
             sw.Write("\"{0}\":[", controllerName);
         }
     }
     else
     {
         writer = CreateXmlWriter(output);
         writer.WriteStartDocument();
         writer.WriteStartElement(controllerName);
         if (r.RequiresRowCount)
             writer.WriteAttributeString("totalRowCount", page.TotalRowCount.ToString());
         if (!(keyIsAvailable))
         {
             writer.WriteAttributeString("pageSize", page.PageSize.ToString());
             writer.WriteAttributeString("pageIndex", page.PageIndex.ToString());
             writer.WriteAttributeString("rowCount", page.Rows.Count.ToString());
             writer.WriteStartElement("items");
         }
     }
     bool firstRow = true;
     foreach (DataField field in page.Fields)
         if (!(String.IsNullOrEmpty(field.DataFormatString)) && !(field.DataFormatString.StartsWith("{")))
             field.DataFormatString = String.Format("{{0:{0}}}", field.DataFormatString);
     foreach (object[] row in page.Rows)
     {
         int index = 0;
         if (json)
         {
             if (firstRow)
                 firstRow = false;
             else
                 sw.Write(",");
             sw.Write("{");
         }
         else
             if (!(keyIsAvailable))
                 writer.WriteStartElement("item");
         bool firstField = true;
         foreach (DataField field in page.Fields)
         {
             if (json)
             {
                 if (firstField)
                     firstField = false;
                 else
                     sw.Write(",");
                 sw.Write("\"{0}\":", field.Name);
                 WriteJSONValue(sw, row[index], field);
             }
             else
             {
                 object v = row[index];
                 if (v != null)
                 {
                     string s = null;
                     if (!(String.IsNullOrEmpty(field.DataFormatString)))
                         s = String.Format(field.DataFormatString, v);
                     else
                         s = Convert.ToString(v);
                     writer.WriteAttributeString(field.Name, s);
                 }
             }
             index++;
         }
         if (json)
             sw.Write("}");
         else
             if (!(keyIsAvailable))
                 writer.WriteEndElement();
         if (keyIsAvailable)
             break;
     }
     if (json)
     {
         if (!(keyIsAvailable))
             sw.Write("]}");
         EndResponsePadding(request, sw);
         sw.Close();
     }
     else
     {
         if (!(keyIsAvailable))
             writer.WriteEndElement();
         writer.WriteEndElement();
         writer.WriteEndDocument();
         writer.Close();
     }
 }
Exemple #20
0
 protected virtual BusinessRules InitBusinessRules(PageRequest request, ViewPage page)
 {
     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);
     return rules;
 }
 public ViewPage GetPage(string controller, string view, PageRequest request)
 {
     return ControllerFactory.CreateDataController().GetPage(controller, view, request);
 }
 private void ExecuteDataExport(ActionArgs args, ActionResult result)
 {
     if (!(String.IsNullOrEmpty(args.CommandArgument)))
     {
         string[] arguments = args.CommandArgument.Split(',');
         if (arguments.Length > 0)
         {
             bool sameController = (args.Controller == arguments[0]);
             args.Controller = arguments[0];
             if (arguments.Length == 1)
                 args.View = "grid1";
             else
                 args.View = arguments[1];
             if (sameController)
                 args.SortExpression = null;
             SelectView(args.Controller, args.View);
         }
     }
     PageRequest request = new PageRequest(-1, -1, null, null);
     request.SortExpression = args.SortExpression;
     request.Filter = args.Filter;
     request.ContextKey = null;
     request.PageIndex = 0;
     request.PageSize = Int32.MaxValue;
     request.View = args.View;
     if (args.CommandName.EndsWith("Template"))
     {
         request.PageSize = 0;
         args.CommandName = "ExportCsv";
     }
     // store export data to a temporary file
     string fileName = Path.GetTempFileName();
     StreamWriter writer = File.CreateText(fileName);
     try
     {
         ViewPage page = new ViewPage(request);
         page.ApplyDataFilter(_config.CreateDataFilter(), args.Controller, args.View, null, null, null);
         if (_serverRules == null)
         {
             _serverRules = _config.CreateBusinessRules();
             if (_serverRules == null)
                 _serverRules = CreateBusinessRules();
         }
         _serverRules.Page = page;
         _serverRules.ExecuteServerRules(request, ActionPhase.Before);
         using (DbConnection connection = CreateConnection())
         {
             DbCommand selectCommand = CreateCommand(connection);
             if ((selectCommand == null) && _serverRules.EnableResultSet)
             {
                 PopulatePageFields(page);
                 EnsurePageFields(page, null);
             }
             ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null);
             DbDataReader reader = ExecuteResultSetReader(page);
             if (reader == null)
                 reader = selectCommand.ExecuteReader();
             if (args.CommandName.EndsWith("Csv"))
                 ExportDataAsCsv(page, reader, writer);
             if (args.CommandName.EndsWith("Rss"))
                 ExportDataAsRss(page, reader, writer);
             if (args.CommandName.EndsWith("Rowset"))
                 ExportDataAsRowset(page, reader, writer);
             reader.Close();
         }
         _serverRules.ExecuteServerRules(request, ActionPhase.After);
     }
     finally
     {
         writer.Close();
     }
     result.Values.Add(new FieldValue("FileName", null, fileName));
 }
 public ViewPage[] GetPageList(PageRequest[] requests)
 {
     return ((DataControllerBase)(ControllerFactory.CreateDataController())).GetPageList(requests);
 }
Exemple #24
0
 void IPlugIn.ProcessPageRequest(PageRequest request, ViewPage page)
 {
     if (page.Rows.Count == 0)
     {
         page.Icons = new string[0];
         return;
     }
     if (!(_requireProcessing))
     {
         List<string> icons = new List<string>();
         for (int i = 0; (i < page.Rows.Count); i++)
         {
             string rowDir = AnnotationPlugIn.GenerateDataRecordPath(request.Controller, page, null, i);
             if (Directory.Exists(rowDir))
                 icons.Add("Attachment");
             else
                 icons.Add(null);
         }
         page.Icons = icons.ToArray();
         return;
     }
     List<DynamicExpression> expressions = new List<DynamicExpression>(page.Expressions);
     DynamicExpression de = new DynamicExpression();
     de.Target = "Annotations";
     de.Scope = DynamicExpressionScope.CategoryVisibility;
     de.Type = DynamicExpressionType.ClientScript;
     de.Test = "!this.get_isInserting()";
     de.ViewId = page.View;
     expressions.Add(de);
     page.Expressions = expressions.ToArray();
     if (!(_retrieveAnnotations))
         return;
     DataField field = page.FindField("_Annotation_AttachmentNew");
     if (field != null)
     {
         int fieldIndex = page.Fields.IndexOf(field);
         string newValue = String.Format("{0},{1}|{2}", request.Controller, field.Name, Regex.Replace(((string)(page.Rows[0][fieldIndex])), "^\\w+\\|(.+)$", "$1"));
         if (field.Name == "_Annotation_AttachmentNew")
             newValue = ("null|" + newValue);
         page.Rows[0][fieldIndex] = newValue;
     }
     string p = AnnotationPlugIn.GenerateDataRecordPath(request.Controller, page, null, 0);
     if (Directory.Exists(p))
     {
         string[] files = Directory.GetFiles(p, "*.xml");
         List<object> values = new List<object>(page.Rows[0]);
         int i = (files.Length - 1);
         while (i >= 0)
         {
             string filename = files[i];
             XPathDocument doc = new XPathDocument(filename);
             XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("/*");
             DataField f = null;
             if (nav.Name == "note")
             {
                 f = new DataField();
                 f.Name = "_Annotation_Note";
                 f.Type = "String";
                 f.HeaderText = String.Format(Localizer.Replace("AnnotationNoteDynamicFieldHeaderText", "{0} written at {1}"), ReadNameAndEmail(nav), Convert.ToDateTime(nav.GetAttribute("timestamp", String.Empty)));
                 f.Columns = 50;
                 f.Rows = 7;
                 f.TextMode = TextInputMode.Note;
                 values.Add(nav.Value);
             }
             else
                 if (nav.Name == "attachment")
                 {
                     f = new DataField();
                     f.Name = "_Annotation_Attachment";
                     f.Type = "Byte[]";
                     f.HeaderText = String.Format(Localizer.Replace("AnnotationAttachmentDynamicFieldHeaderText", "{0} attached <b>{1}</b> at {2}"), ReadNameAndEmail(nav), nav.GetAttribute("fileName", String.Empty), Convert.ToDateTime(nav.GetAttribute("timestamp", String.Empty)));
                     f.OnDemand = true;
                     f.OnDemandHandler = "AnnotationPlugIn";
                     f.OnDemandStyle = OnDemandDisplayStyle.Link;
                     if (nav.GetAttribute("contentType", String.Empty).StartsWith("image/"))
                         f.OnDemandStyle = OnDemandDisplayStyle.Thumbnail;
                     f.CategoryIndex = (page.Categories.Count - 1);
                     values.Add(nav.GetAttribute("value", String.Empty));
                 }
             if (f != null)
             {
                 f.Name = (f.Name + Path.GetFileNameWithoutExtension(filename));
                 f.AllowNulls = true;
                 f.CategoryIndex = (page.Categories.Count - 1);
                 if (!(Controller.UserIsInRole("Administrators")))
                     f.ReadOnly = true;
                 page.Fields.Add(f);
             }
             i = (i - 1);
         }
         page.Rows[0] = values.ToArray();
         if (files.Length > 0)
         {
             page.Categories[(page.Categories.Count - 1)].Tab = Localizer.Replace("AnnotationTab", "Notes & Attachments");
             expressions.RemoveAt((expressions.Count - 1));
             page.Expressions = expressions.ToArray();
         }
     }
     else
     {
         de.Test = "this.get_isEditing() && this.get_view()._displayAnnotations";
         ActionGroup g = new ActionGroup();
         page.ActionGroups.Add(g);
         g.Scope = "ActionBar";
         g.Flat = true;
         Action a = new Action();
         g.Actions.Add(a);
         a.WhenLastCommandName = "Edit";
         a.WhenView = page.View;
         a.CommandName = "ClientScript";
         a.CommandArgument = "this.get_view()._displayAnnotations=true;this._focusedFieldName = \'_Annotation_No" +
             "teNew\';this._raiseSelectedDelayed=false;";
         a.HeaderText = Localizer.Replace("AnnotationActionHeaderText", "Annotate");
         a.CssClass = "AttachIcon";
         a.WhenClientScript = "this.get_view()._displayAnnotations!=true;";
     }
 }
Exemple #25
0
        private void ExecuteDataExport(ActionArgs args, ActionResult result)
        {
            if (!(String.IsNullOrEmpty(args.CommandArgument)))
            {
                string[] arguments = args.CommandArgument.Split(',');
                if (arguments.Length > 0)
                {
                    bool sameController = (args.Controller == arguments[0]);
                    args.Controller = arguments[0];
                    if (arguments.Length == 1)
                    {
                        args.View = "grid1";
                    }
                    else
                    {
                        args.View = arguments[1];
                    }
                    if (sameController)
                    {
                        args.SortExpression = null;
                    }
                    SelectView(args.Controller, args.View);
                }
            }
            PageRequest request = new PageRequest(-1, -1, null, null);

            request.SortExpression = args.SortExpression;
            request.Filter         = args.Filter;
            request.ContextKey     = null;
            request.PageIndex      = 0;
            request.PageSize       = Int32.MaxValue;
            request.View           = args.View;
            if (args.CommandName.EndsWith("Template"))
            {
                request.PageSize = 0;
                args.CommandName = "ExportCsv";
            }
            // store export data to a temporary file
            string       fileName = Path.GetTempFileName();
            StreamWriter writer   = File.CreateText(fileName);

            try
            {
                ViewPage page = new ViewPage(request);
                page.ApplyDataFilter(_config.CreateDataFilter(), args.Controller, args.View, null, null, null);
                if (_serverRules == null)
                {
                    _serverRules = _config.CreateBusinessRules();
                    if (_serverRules == null)
                    {
                        _serverRules = CreateBusinessRules();
                    }
                }
                _serverRules.Page = page;
                _serverRules.ExecuteServerRules(request, ActionPhase.Before);
                using (DbConnection connection = CreateConnection())
                {
                    DbCommand selectCommand = CreateCommand(connection);
                    if ((selectCommand == null) && _serverRules.EnableResultSet)
                    {
                        PopulatePageFields(page);
                        EnsurePageFields(page, null);
                    }
                    ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null);
                    DbDataReader reader = ExecuteResultSetReader(page);
                    if (reader == null)
                    {
                        reader = selectCommand.ExecuteReader();
                    }
                    if (args.CommandName.EndsWith("Csv"))
                    {
                        ExportDataAsCsv(page, reader, writer);
                    }
                    if (args.CommandName.EndsWith("Rss"))
                    {
                        ExportDataAsRss(page, reader, writer);
                    }
                    if (args.CommandName.EndsWith("Rowset"))
                    {
                        ExportDataAsRowset(page, reader, writer);
                    }
                    reader.Close();
                }
                _serverRules.ExecuteServerRules(request, ActionPhase.After);
            }
            finally
            {
                writer.Close();
            }
            result.Values.Add(new FieldValue("FileName", null, fileName));
        }