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();
            }
        }
        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;";
            }
        }
        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);
                string type   = RowsetTypeMap[field.Type];
                string dbType = null;
                if ("{0:c}".Equals(field.DataFormatString, StringComparison.CurrentCultureIgnoreCase))
                {
                    dbType = "currency";
                }
                else
                if (!(String.IsNullOrEmpty(field.DataFormatString)) && field.Type != "DateTime")
                {
                    type = "string";
                }
                output.WriteAttributeString("type", dt, type);
                output.WriteAttributeString("dbtype", rs, dbType);
                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();
        }
        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();
        }
Esempio n. 5
0
        private void AppendWhereExpressions(StringBuilder sb, DbCommand command, ViewPage page, SelectClauseDictionary expressions, FieldValue[] values)
        {
            sb.AppendLine();
            sb.Append("where");
            bool firstField = true;

            foreach (FieldValue v in values)
            {
                DataField field = page.FindField(v.Name);
                if ((field != null) && field.IsPrimaryKey)
                {
                    sb.AppendLine();
                    if (firstField)
                    {
                        firstField = false;
                    }
                    else
                    {
                        sb.Append("and ");
                    }
                    sb.AppendFormat(RemoveTableAliasFromExpression(expressions[v.Name]));
                    sb.AppendFormat("={0}p{1}", _parameterMarker, command.Parameters.Count);
                    DbParameter parameter = command.CreateParameter();
                    parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                    AssignParameterValue(parameter, field.Type, v.OldValue);
                    command.Parameters.Add(parameter);
                }
            }
            bool ignorePrimaryKeyInWhere = false;

            if (firstField)
            {
                foreach (FieldValue fv in values)
                {
                    if (fv.Name == "_IgnorePrimaryKeyInWhere")
                    {
                        ignorePrimaryKeyInWhere = true;
                        break;
                    }
                }
                // if the first field has not been processed then a primary key has not been provided
                if (!(ignorePrimaryKeyInWhere))
                {
                    throw new Exception("A primary key field value is not provided.");
                }
            }
            if (ignorePrimaryKeyInWhere || _config.ConflictDetectionEnabled)
            {
                foreach (FieldValue v in values)
                {
                    DataField field = page.FindField(v.Name);
                    if ((field != null) && (!((field.IsPrimaryKey || field.OnDemand)) && !(v.ReadOnly)))
                    {
                        sb.AppendLine();
                        if (firstField)
                        {
                            firstField = false;
                        }
                        else
                        {
                            sb.Append("and ");
                        }
                        sb.Append(RemoveTableAliasFromExpression(expressions[v.Name]));
                        if (v.OldValue == null)
                        {
                            sb.Append(" is null");
                        }
                        else
                        {
                            sb.AppendFormat("={0}p{1}", _parameterMarker, command.Parameters.Count);
                            DbParameter parameter = command.CreateParameter();
                            parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                            AssignParameterValue(parameter, field.Type, v.OldValue);
                            command.Parameters.Add(parameter);
                        }
                    }
                }
            }
            sb.AppendLine();
        }
Esempio n. 6
0
        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) || (operation == "~")) && (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 == "~")
                                {
                                    paramValue = Convert.ToString(StringToValue(paramValue));
                                    string splitExpression = ",|;";
                                    if (paramValue.Contains(",") && paramValue.Contains(";"))
                                    {
                                        splitExpression = ";";
                                    }
                                    string[] phrases     = Regex.Split(paramValue, splitExpression);
                                    bool     firstPhrase = true;
                                    foreach (string phrase in phrases)
                                    {
                                        if (firstPhrase)
                                        {
                                            firstPhrase = false;
                                        }
                                        else
                                        {
                                            sb.AppendLine("or");
                                        }
                                        sb.AppendLine("(");
                                        bool            firstWord   = true;
                                        string[]        phraseParts = Regex.Split(phrase, "\\s+");
                                        System.DateTime paramValueAsDate;
                                        if (field.Type.StartsWith("Date") && SqlStatement.TryParseDate(command.GetType(), phrase, out paramValueAsDate))
                                        {
                                            phraseParts = new string[] {
                                                phrase
                                            }
                                        }
                                        ;
                                        foreach (string paramValueWord in phraseParts)
                                        {
                                            string      pv = paramValueWord.Trim();
                                            bool        paramValueIsDate = SqlStatement.TryParseDate(command.GetType(), pv, out paramValueAsDate);
                                            bool        firstTry         = true;
                                            DbParameter parameter        = null;
                                            if (!(paramValueIsDate))
                                            {
                                                pv = SqlStatement.EscapePattern(command, pv);
                                            }
                                            if (!(pv.Contains("%")))
                                            {
                                                pv = String.Format("%{0}%", pv);
                                            }
                                            if (firstWord)
                                            {
                                                firstWord = false;
                                            }
                                            else
                                            {
                                                sb.Append("and");
                                            }
                                            sb.Append("(");
                                            foreach (DataField tf in page.Fields)
                                            {
                                                if ((tf.AllowQBE && String.IsNullOrEmpty(tf.AliasName)) && (!((tf.IsPrimaryKey && tf.Hidden)) && (!(tf.Type.StartsWith("Date")) || paramValueIsDate)))
                                                {
                                                    if ((parameter == null) || command.GetType().FullName.Contains("ManagedDataAccess"))
                                                    {
                                                        parameter = command.CreateParameter();
                                                        parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                                        parameter.DbType        = DbType.String;
                                                        command.Parameters.Add(parameter);
                                                        parameter.Value = pv;
                                                    }
                                                    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.DateTime;
                                                        command.Parameters.Add(dateParameter);
                                                        dateParameter.Value = paramValueAsDate;
                                                        sb.AppendFormat("({0} = {1})", expressions[tf.ExpressionName()], dateParameter.ParameterName);
                                                    }
                                                    else
                                                    if (DatabaseEngineIs(command, "Oracle", "DB2"))
                                                    {
                                                        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(")");
                                        }
                                        sb.AppendLine(")");
                                    }
                                }
                                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);
                                            if ((parameter.DbType == DbType.Binary) && (parameter.Value is Guid))
                                            {
                                                parameter.Value = ((Guid)(parameter.Value)).ToByteArray();
                                            }
                                        }
                                        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(")");
            }
        }
Esempio n. 7
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);
 }
        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);
            }
        }
        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);
        }