Esempio n. 1
0
        void IPlugIn.PreProcessPageRequest(PageRequest request, ViewPage page)
        {
            XPathNavigator view = _config.Navigator.SelectSingleNode(String.Format("//c:view[@id=\'{0}\' and @type=\'Form\']/c:categories", request.View), _config.Resolver);

            if ((view != null) && !(request.IsModal))
            {
                _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", "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", "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", "Notes and Attachments");
                writer.WriteElementString("description", ns, "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();
            }
        }
Esempio n. 2
0
        void IPlugIn.ProcessPageRequest(PageRequest request, ViewPage page)
        {
            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 = "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", RegexOptions.Compiled));
                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("{0} ({1}) written at {2}", nav.GetAttribute("email", String.Empty), nav.GetAttribute("username", String.Empty), 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("{0} ({1}) attached <b>{2}</b> at {3}", nav.GetAttribute("email", String.Empty), nav.GetAttribute("username", String.Empty), 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 (!(HttpContext.Current.User.IsInRole("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 = "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       = "Annotate";
                a.CssClass         = "AttachIcon";
                a.WhenClientScript = "this.get_view()._displayAnnotations!=true;";
            }
        }
Esempio n. 3
0
        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);
        }