protected virtual void AppendRecursiveFilter(ViewPage page) { if (this._viewType != "Tree") { return; } DataField recursiveField = null; if (page.Filter != null) { foreach (string filterExpression in page.Filter) { Match filterMatch = Regex.Match(filterExpression, "(?\'Alias\'\\w+):"); if (filterMatch.Success) { DataField f = page.FindField(filterMatch.Groups["Alias"].Value); if ((f != null) && (f.ItemsDataController == page.Controller)) { recursiveField = f; break; } } } } if (recursiveField == null) { foreach (DataField f in page.Fields) { if (f.ItemsDataController == page.Controller) { if (!(String.IsNullOrEmpty(_viewFilter))) { _viewFilter = String.Format("({0})and", _viewFilter); } _viewFilter = String.Format("{0}({1} is null)", _viewFilter, f.Name); break; } } } }
private void ResolveLookups(ImportLookupDictionary lookups) { foreach (string fieldName in lookups.Keys) { DataField lookupField = lookups[fieldName]; if ((lookupField.Items.Count == 0) && (String.IsNullOrEmpty(lookupField.ItemsDataValueField) || String.IsNullOrEmpty(lookupField.ItemsDataTextField))) { PageRequest lookupRequest = new PageRequest(); lookupRequest.Controller = lookupField.ItemsDataController; lookupRequest.View = lookupField.ItemsDataView; lookupRequest.RequiresMetaData = true; ViewPage lp = ControllerFactory.CreateDataController().GetPage(lookupRequest.Controller, lookupRequest.View, lookupRequest); if (String.IsNullOrEmpty(lookupField.ItemsDataValueField)) { foreach (DataField f in lp.Fields) { if (f.IsPrimaryKey) { lookupField.ItemsDataValueField = f.Name; break; } } } if (String.IsNullOrEmpty(lookupField.ItemsDataTextField)) { foreach (DataField f in lp.Fields) { if ((!(f.IsPrimaryKey) && !(f.Hidden)) && (!(f.AllowNulls) || (f.Type == "String"))) { lookupField.ItemsDataTextField = f.Name; break; } } } } } }
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); } }
protected virtual void AppendFilterExpressionsToWhere(StringBuilder sb, ViewPage page, DbCommand command, SelectClauseDictionary expressions, string whereClause) { bool firstCriteria = String.IsNullOrEmpty(_viewFilter); if (!(firstCriteria)) { EnsureWhereKeyword(sb); sb.AppendLine("("); sb.Append(ProcessViewFilter(page, command, expressions)); } if (page.Filter != null) { foreach (string filterExpression in page.Filter) { Match filterMatch = FilterExpressionRegex.Match(filterExpression); if (filterMatch.Success) { // "ProductName:?g", "CategoryCategoryName:=Condiments\x00=Seafood" bool firstValue = true; string fieldOperator = " or "; if (Regex.IsMatch(filterMatch.Groups["Values"].Value, ">|<")) { fieldOperator = " and "; } Match valueMatch = FilterValueRegex.Match(filterMatch.Groups["Values"].Value); while (valueMatch.Success) { string alias = filterMatch.Groups["Alias"].Value; string operation = valueMatch.Groups["Operation"].Value; string paramValue = valueMatch.Groups["Value"].Value; DataField field = page.FindField(alias); if (((field != null) && field.AllowQBE) && (page.DistinctValueFieldName != field.Name || (page.AllowDistinctFieldInFilter || page.CustomFilteredBy(field.Name)))) { if (firstValue) { if (firstCriteria) { EnsureWhereKeyword(sb); sb.AppendLine("("); firstCriteria = false; } else { sb.Append("and "); } sb.Append("("); firstValue = false; } else { sb.Append(fieldOperator); } if (operation == "~") { bool firstWord = true; paramValue = Convert.ToString(StringToValue(paramValue)); foreach (string paramValueWord in paramValue.Split(' ')) { string pv = paramValueWord.Trim(); DateTime paramValueAsDate; bool paramValueIsDate = SqlStatement.TryParseDate(command.GetType(), pv, out paramValueAsDate); bool firstTry = true; DbParameter parameter = command.CreateParameter(); parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count); parameter.DbType = DbType.String; command.Parameters.Add(parameter); if (!(paramValueIsDate)) { pv = SqlStatement.EscapePattern(command, pv); } if (!(pv.Contains("%"))) { pv = String.Format("%{0}%", pv); } parameter.Value = pv; if (firstWord) { firstWord = false; } else { sb.Append("and"); } sb.Append("("); foreach (DataField tf in page.Fields) { if (tf.AllowQBE && (!((tf.IsPrimaryKey && tf.Hidden)) && (!(tf.Type.StartsWith("Date")) || paramValueIsDate))) { if (firstTry) { firstTry = false; } else { sb.Append(" or "); } if (tf.Type.StartsWith("Date")) { DbParameter dateParameter = command.CreateParameter(); dateParameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count); dateParameter.DbType = DbType.String; command.Parameters.Add(dateParameter); dateParameter.Value = paramValueAsDate; sb.AppendFormat("({0} = {1})", expressions[tf.ExpressionName()], dateParameter.ParameterName); } else if (command.GetType().Name.Contains("Oracle")) { sb.AppendFormat("(upper({0}) like {1})", expressions[tf.ExpressionName()], parameter.ParameterName); parameter.Value = Convert.ToString(parameter.Value).ToUpper(); } else { sb.AppendFormat("({0} like {1})", expressions[tf.ExpressionName()], parameter.ParameterName); } } } sb.Append(")"); } } else if (operation.StartsWith("$")) { sb.Append(FilterFunctions.Replace(command, expressions, String.Format("{0}({1}$comma${2})", operation.TrimEnd('$'), alias, Convert.ToBase64String(Encoding.UTF8.GetBytes(paramValue))))); } else { DbParameter parameter = command.CreateParameter(); parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count); AssignParameterDbType(parameter, field.Type); sb.Append(expressions[field.ExpressionName()]); bool requiresRangeAdjustment = ((operation == "=") && (field.Type.StartsWith("DateTime") && !(StringIsNull(paramValue)))); if ((operation == "<>") && StringIsNull(paramValue)) { sb.Append(" is not null "); } else if ((operation == "=") && StringIsNull(paramValue)) { sb.Append(" is null "); } else { if (operation == "*") { sb.Append(" like "); parameter.DbType = DbType.String; if (!(paramValue.Contains("%"))) { paramValue = (SqlStatement.EscapePattern(command, paramValue) + "%"); } } else if (requiresRangeAdjustment) { sb.Append(">="); } else { sb.Append(operation); } try { parameter.Value = StringToValue(field, paramValue); } catch (Exception) { parameter.Value = DBNull.Value; } sb.Append(parameter.ParameterName); command.Parameters.Add(parameter); if (requiresRangeAdjustment) { DbParameter rangeParameter = command.CreateParameter(); AssignParameterDbType(rangeParameter, field.Type); rangeParameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count); sb.Append(String.Format(" and {0} < {1}", expressions[field.ExpressionName()], rangeParameter.ParameterName)); if (field.Type == "DateTimeOffset") { DateTime dt = Convert.ToDateTime(parameter.Value); parameter.Value = new DateTimeOffset(dt).AddHours(-14); rangeParameter.Value = new DateTimeOffset(dt).AddDays(1).AddHours(14); } else { rangeParameter.Value = Convert.ToDateTime(parameter.Value).AddDays(1); } command.Parameters.Add(rangeParameter); } } } } valueMatch = valueMatch.NextMatch(); } if (!(firstValue)) { sb.AppendLine(")"); } } } } if (!(firstCriteria)) { sb.AppendLine(")"); if (!(String.IsNullOrEmpty(whereClause))) { sb.Append("and "); } } if (!(String.IsNullOrEmpty(whereClause))) { sb.AppendLine("("); sb.AppendLine(whereClause); sb.AppendLine(")"); } }
public virtual void Process(string fileName, string controller, string view, string notify, List <string> userMapping) { BeforeProcess(fileName, controller, view, notify, userMapping); string logFileName = Path.GetTempFileName(); StreamWriter log = File.CreateText(logFileName); log.WriteLine("{0:s} Import process started.", DateTime.Now); // retrieve metadata PageRequest request = new PageRequest(); request.Controller = controller; request.View = view; request.RequiresMetaData = true; ViewPage page = ControllerFactory.CreateDataController().GetPage(controller, view, request); // open data reader and enumerate fields OleDbDataReader reader = OpenRead(fileName, "*"); ImportMapDictionary map = new ImportMapDictionary(); ImportLookupDictionary lookups = new ImportLookupDictionary(); EnumerateFields(reader, page, map, lookups, userMapping); // resolve lookup data value field and data text fields ResolveLookups(lookups); // insert records from the file int recordCount = 0; int errorCount = 0; NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat; Regex numberCleanupRegex = new Regex(String.Format("[^\\d\\{0}\\{1}\\{2}]", nfi.CurrencyDecimalSeparator, nfi.NegativeSign, nfi.NumberDecimalSeparator)); while (reader.Read()) { ActionArgs args = new ActionArgs(); args.Controller = controller; args.View = view; args.LastCommandName = "New"; args.CommandName = "Insert"; List <FieldValue> values = new List <FieldValue>(); foreach (int index in map.Keys) { DataField field = map[index]; object v = reader[index]; if (DBNull.Value.Equals(v)) { v = null; } else if (field.Type != "String" && (v is string)) { string s = ((string)(v)); if (field.Type == "Boolean") { v = s.ToLower(); } else if (!(field.Type.StartsWith("Date")) && field.Type != "Time") { v = numberCleanupRegex.Replace(s, String.Empty); } } if (v != null) { DataField lookupField = null; if (lookups.TryGetValue(field.Name, out lookupField)) { if (lookupField.Items.Count > 0) { // copy static values foreach (object[] item in lookupField.Items) { if (Convert.ToString(item[1]).Equals(Convert.ToString(v), StringComparison.CurrentCultureIgnoreCase)) { values.Add(new FieldValue(lookupField.Name, item[0])); } } } else { PageRequest lookupRequest = new PageRequest(); lookupRequest.Controller = lookupField.ItemsDataController; lookupRequest.View = lookupField.ItemsDataView; lookupRequest.RequiresMetaData = true; lookupRequest.PageSize = 1; lookupRequest.Filter = new string[] { String.Format("{0}:={1}{2}", lookupField.ItemsDataTextField, v, Convert.ToChar(0)) }; ViewPage vp = ControllerFactory.CreateDataController().GetPage(lookupRequest.Controller, lookupRequest.View, lookupRequest); if (vp.Rows.Count > 0) { values.Add(new FieldValue(lookupField.ItemsDataValueField, vp.Rows[0][vp.Fields.IndexOf(vp.FindField(lookupField.ItemsDataValueField))])); } } } else { values.Add(new FieldValue(field.Name, v)); } } } recordCount++; if (values.Count > 0) { args.Values = values.ToArray(); ActionResult r = ControllerFactory.CreateDataController().Execute(controller, view, args); if (r.Errors.Count > 0) { log.WriteLine("{0:s} Error importing record #{1}.", DateTime.Now, recordCount); log.WriteLine(); foreach (string s in r.Errors) { log.WriteLine(s); } foreach (FieldValue v in values) { if (v.Modified) { log.WriteLine("{0}={1};", v.Name, v.Value); } } log.WriteLine(); errorCount++; } } else { log.WriteLine("{0:s} Record #1 has been ignored.", DateTime.Now, recordCount); errorCount++; } } reader.Close(); log.WriteLine("{0:s} Processed {1} records. Detected {2} errors.", DateTime.Now, recordCount, errorCount); log.Close(); if (!(String.IsNullOrEmpty(notify))) { string[] recipients = notify.Split(','); SmtpClient client = new SmtpClient(); foreach (string s in recipients) { string address = s.Trim(); if (!(String.IsNullOrEmpty(address))) { MailMessage message = new MailMessage(); try { message.To.Add(new MailAddress(address)); message.Subject = String.Format("Import of {0} has been completed", controller); message.Body = File.ReadAllText(logFileName); client.Send(message); } catch (Exception) { } } } } File.Delete(logFileName); AfterProcess(fileName, controller, view, notify, userMapping); }
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); } 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); } command.CommandText = originalCommandText; command.Parameters.Clear(); if (_config.PlugIn != null) { _config.PlugIn.ProcessArguments(args, result, page); } } } 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); } 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); }
private void EnumerateFields(OleDbDataReader reader, ViewPage page, ImportMapDictionary map, ImportLookupDictionary lookups, List <string> userMapping) { List <String> mappedFields = new List <string>(); for (int i = 0; (i < reader.FieldCount); i++) { string fieldName = reader.GetName(i); DataField field = null; bool autoDetect = true; if (userMapping != null) { string mappedFieldName = userMapping[i]; autoDetect = String.IsNullOrEmpty(mappedFieldName); if (!(autoDetect)) { fieldName = mappedFieldName; } } if (autoDetect) { foreach (DataField f in page.Fields) { if (fieldName.Equals(f.HeaderText, StringComparison.CurrentCultureIgnoreCase) || fieldName.Equals(f.Label, StringComparison.CurrentCultureIgnoreCase)) { field = f; break; } } } if (field == null) { field = page.FindField(fieldName); } if (field != null) { if (!(String.IsNullOrEmpty(field.AliasName))) { field = page.FindField(field.AliasName); } if (!(field.ReadOnly)) { if (!(mappedFields.Contains(field.Name))) { map.Add(i, field); mappedFields.Add(field.Name); } } else { foreach (DataField f in page.Fields) { if (f.AliasName == field.Name) { map.Add(i, field); lookups.Add(field.Name, f); break; } } } } } }
void IPlugIn.ProcessPageRequest(PageRequest request, ViewPage page) { if (page.Rows.Count == 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 = Localizer.Replace("AnnotationCategoryHeaderText", "Notes and Attachments"); 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\';"; a.HeaderText = Localizer.Replace("AnnotationActionHeaderText", "Annotate"); a.CssClass = "AttachIcon"; a.WhenClientScript = "this.get_view()._displayAnnotations!=true;"; } }
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(); if (rules != null) { rules.Page = page; rules.BeforeSelect(request); } else { CreateBusinessRules().ExecuteServerRules(request, ActionPhase.Before); } using (DbConnection connection = CreateConnection()) { if (page.RequiresRowCount && !((request.Inserting || request.DoesNotRequireData))) { 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))) { aggregates[i] = v; } } } page.Aggregates = aggregates; } reader.Close(); } } if (page.RequiresMetaData) { PopulatePageCategories(page); } DbCommand selectCommand = CreateCommand(connection); ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null); if ((page.PageSize > 0) && !((request.Inserting || request.DoesNotRequireData))) { 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 { v = ConvertObjectToValue(v); } values[i] = v; } if (!(String.IsNullOrEmpty(field.SourceFields))) { values[i] = CreateValueFromSourceFields(field, reader); } } 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 (rules != null) { IRowHandler rowHandler = rules; if (request.Inserting) { if (rowHandler.SupportsNewRow(request)) { page.NewRow = new object[page.Fields.Count]; 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); rules.Result.Merge(page); } else { CreateBusinessRules().ExecuteServerRules(request, ActionPhase.After); } return(page); }
public void Merge(ViewPage page) { page.ClientScript = ClientScript; }
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))) { _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("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(); } }
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); 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); }
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; 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); using (DbConnection connection = CreateConnection()) { DbCommand selectCommand = CreateCommand(connection); ConfigureCommand(selectCommand, page, CommandConfigurationType.Select, null); DbDataReader 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(); } } finally { writer.Close(); } result.Values.Add(new FieldValue("FileName", null, fileName)); }
private void ExportDataAsCsv(ViewPage page, DbDataReader reader, StreamWriter writer) { bool firstField = true; for (int i = 0; (i < page.Fields.Count); i++) { DataField field = page.Fields[i]; if (!(field.Hidden)) { if (firstField) { firstField = false; } else { writer.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator); } if (!(String.IsNullOrEmpty(field.AliasName))) { field = page.FindField(field.AliasName); } writer.Write("\"{0}\"", field.Label.Replace("\"", "\"\"")); } field.NormalizeDataFormatString(); } writer.WriteLine(); while (reader.Read()) { firstField = true; for (int j = 0; (j < page.Fields.Count); j++) { DataField field = page.Fields[j]; if (!(field.Hidden)) { if (firstField) { firstField = false; } else { writer.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator); } if (!(String.IsNullOrEmpty(field.AliasName))) { field = page.FindField(field.AliasName); } string text = String.Empty; object v = reader[field.Name]; if (!(DBNull.Value.Equals(v))) { if (!(String.IsNullOrEmpty(field.DataFormatString))) { text = String.Format(field.DataFormatString, v); } else { text = Convert.ToString(v); } writer.Write("\"{0}\"", text.Replace("\"", "\"\"")); } else { writer.Write("\"\""); } } } writer.WriteLine(); } }
private void ExportDataAsRss(ViewPage page, DbDataReader reader, StreamWriter writer) { string appPath = Regex.Replace(HttpContext.Current.Request.Url.AbsoluteUri, "^(.+)Export.ashx.+$", "$1", RegexOptions.IgnoreCase); XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = false; XmlWriter output = XmlWriter.Create(writer, settings); output.WriteStartDocument(); output.WriteStartElement("rss"); output.WriteAttributeString("version", "2.0"); output.WriteStartElement("channel"); output.WriteElementString("title", ((string)(_view.Evaluate("string(concat(/c:dataController/@label, \' | \', @label))", Resolver)))); output.WriteElementString("lastBuildDate", DateTime.Now.ToString("r")); output.WriteElementString("language", System.Threading.Thread.CurrentThread.CurrentCulture.Name.ToLower()); int rowCount = 0; while ((rowCount < MaximumRssItems) && reader.Read()) { output.WriteStartElement("item"); bool hasTitle = false; bool hasPubDate = false; StringBuilder desc = new StringBuilder(); for (int i = 0; (i < page.Fields.Count); i++) { DataField field = page.Fields[i]; if (!(field.Hidden)) { if (rowCount == 0) { field.NormalizeDataFormatString(); } if (!(String.IsNullOrEmpty(field.AliasName))) { field = page.FindField(field.AliasName); } string text = String.Empty; object v = reader[field.Name]; if (!(DBNull.Value.Equals(v))) { if (!(String.IsNullOrEmpty(field.DataFormatString))) { text = String.Format(field.DataFormatString, v); } else { text = Convert.ToString(v); } } if (!(hasPubDate) && (field.Type == "DateTime")) { hasPubDate = true; if (!(String.IsNullOrEmpty(text))) { output.WriteElementString("pubDate", ((DateTime)(reader[field.Name])).ToString("r")); } } if (!(hasTitle)) { hasTitle = true; output.WriteElementString("title", text); StringBuilder link = new StringBuilder(); link.Append(_config.Evaluate("string(/c:dataController/@name)")); foreach (DataField pkf in page.Fields) { if (pkf.IsPrimaryKey) { link.Append(String.Format("&{0}={1}", pkf.Name, reader[pkf.Name])); } } string itemGuid = String.Format("{0}Details.aspx?l={1}", appPath, HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.Default.GetBytes(link.ToString())))); output.WriteElementString("link", itemGuid); output.WriteElementString("guid", itemGuid); } else if (!(String.IsNullOrEmpty(field.OnDemandHandler)) && (field.OnDemandStyle == OnDemandDisplayStyle.Thumbnail)) { if (text.Equals("1")) { desc.AppendFormat("{0}:<br /><img src=\"{1}Blob.ashx?{2}=t", HttpUtility.HtmlEncode(field.Label), appPath, field.OnDemandHandler); foreach (DataField f in page.Fields) { if (f.IsPrimaryKey) { desc.Append("|"); desc.Append(reader[f.Name]); } } desc.Append("\" style=\"width:92px;height:71px;\"/><br />"); } } else { desc.AppendFormat("{0}: {1}<br />", HttpUtility.HtmlEncode(field.Label), HttpUtility.HtmlEncode(text)); } } } output.WriteStartElement("description"); output.WriteCData(String.Format("<span style=\\\"font-size:small;\\\">{0}</span>", desc.ToString())); output.WriteEndElement(); output.WriteEndElement(); rowCount++; } output.WriteEndElement(); output.WriteEndElement(); output.WriteEndDocument(); output.Close(); }
private void ExportDataAsRowset(ViewPage page, DbDataReader reader, StreamWriter writer) { string s = "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"; string dt = "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"; string rs = "urn:schemas-microsoft-com:rowset"; string z = "#RowsetSchema"; XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = false; XmlWriter output = XmlWriter.Create(writer, settings); output.WriteStartDocument(); output.WriteStartElement("xml"); output.WriteAttributeString("xmlns", "s", null, s); output.WriteAttributeString("xmlns", "dt", null, dt); output.WriteAttributeString("xmlns", "rs", null, rs); output.WriteAttributeString("xmlns", "z", null, z); // declare rowset schema output.WriteStartElement("Schema", s); output.WriteAttributeString("id", "RowsetSchema"); output.WriteStartElement("ElementType", s); output.WriteAttributeString("name", "row"); output.WriteAttributeString("content", "eltOnly"); output.WriteAttributeString("CommandTimeout", rs, "60"); List <DataField> fields = new List <DataField>(); foreach (DataField field in page.Fields) { if (!((field.Hidden || field.OnDemand)) && !(fields.Contains(field))) { DataField aliasField = field; if (!(String.IsNullOrEmpty(field.AliasName))) { aliasField = page.FindField(field.AliasName); } fields.Add(aliasField); } } int number = 1; foreach (DataField field in fields) { field.NormalizeDataFormatString(); output.WriteStartElement("AttributeType", s); output.WriteAttributeString("name", field.Name); output.WriteAttributeString("number", rs, number.ToString()); output.WriteAttributeString("nullable", rs, "true"); output.WriteAttributeString("name", rs, field.Label); output.WriteStartElement("datatype", s); output.WriteAttributeString("type", dt, RowsetTypeMap[field.Type]); if (field.DataFormatString == "{0:c}") { output.WriteAttributeString("dbtype", rs, "currency"); } output.WriteEndElement(); output.WriteEndElement(); number++; } output.WriteStartElement("extends", s); output.WriteAttributeString("type", "rs:rowbase"); output.WriteEndElement(); output.WriteEndElement(); output.WriteEndElement(); // output rowset data output.WriteStartElement("data", rs); while (reader.Read()) { output.WriteStartElement("row", z); foreach (DataField field in fields) { object v = reader[field.Name]; if (!(DBNull.Value.Equals(v))) { if (!(String.IsNullOrEmpty(field.DataFormatString)) && !(((field.DataFormatString == "{0:d}") || (field.DataFormatString == "{0:c}")))) { output.WriteAttributeString(field.Name, String.Format(field.DataFormatString, v)); } else if (field.Type == "DateTime") { output.WriteAttributeString(field.Name, ((DateTime)(v)).ToString("s")); } else { output.WriteAttributeString(field.Name, v.ToString()); } } } output.WriteEndElement(); } output.WriteEndElement(); output.WriteEndElement(); output.WriteEndDocument(); output.Close(); }