Example #1
0
 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;
                     }
                 }
             }
         }
     }
 }
Example #2
0
        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);
            }
        }
Example #3
0
 public virtual void ProcessPageRequest(PageRequest request, ViewPage page)
 {
 }
Example #4
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 = 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("AnnotationNoteFieldHeaderText", "{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(Localizer.Replace("AnnotationAttachmentFieldHeaderText", "{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 (!(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;";
            }
        }
Example #5
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) && (request.PageSize > 0)))
            {
                _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();
            }
        }
Example #6
0
 public bool PopulateStaticItems(DataField field, FieldValue[] contextValues)
 {
     if ((!(String.IsNullOrEmpty(field.ItemsDataController)) && field.ItemsStyle != "Lookup") && (String.IsNullOrEmpty(field.ContextFields) || (contextValues != null)))
     {
         string[] filter = null;
         if (!(String.IsNullOrEmpty(field.ContextFields)))
         {
             List <string> contextFilter = new List <string>();
             Match         m             = Regex.Match(field.ContextFields, "(\\w+)=(.+?)($|,)", RegexOptions.Compiled);
             while (m.Success)
             {
                 Match vm = Regex.Match(m.Groups[2].Value, "^\'(.+?)\'$", RegexOptions.Compiled);
                 if (vm.Success)
                 {
                     contextFilter.Add(String.Format("{0}:={1}", m.Groups[1].Value, vm.Groups[1].Value));
                 }
                 else
                 {
                     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, null, 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+)", RegexOptions.Compiled);
             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++)
             {
                 values[i] = row[fieldIndexes[i]];
             }
             field.Items.Add(values);
         }
         if (String.IsNullOrEmpty(field.ItemsDataTextField))
         {
             SortedDictionary <string, object[]> sortedList = new SortedDictionary <string, object[]>();
             foreach (object[] item in field.Items)
             {
                 string s = Convert.ToString(item[1]);
                 if (!(sortedList.ContainsKey(s)))
                 {
                     sortedList.Add(s, item);
                 }
             }
             field.Items.Clear();
             foreach (object[] item in sortedList.Values)
             {
                 field.Items.Add(item);
             }
         }
         return(true);
     }
     return(false);
 }
Example #7
0
 public bool PopulateStaticItems(DataField field, FieldValue[] contextValues)
 {
     if (field.SupportsStaticItems() && (String.IsNullOrEmpty(field.ContextFields) || (contextValues != null)))
     {
         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
                     {
                         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);
 }
Example #8
0
        void IPlugIn.ProcessArguments(ActionArgs args, ActionResult result, ViewPage page)
        {
            if (_annotations.Count == 0)
            {
                return;
            }
            string p = AnnotationPlugIn.GenerateDataRecordPath(args.Controller, page, args.Values, 0);

            if (!(Directory.Exists(p)))
            {
                Directory.CreateDirectory(p);
            }
            foreach (FieldValue v in _annotations)
            {
                Match m = Regex.Match(v.Name, "^_Annotation_(Note)(New|\\w+)$", RegexOptions.Compiled);
                if (m.Success)
                {
                    if (m.Groups[1].Value == "Note")
                    {
                        string fileName = m.Groups[2].Value;
                        if (fileName == "New")
                        {
                            fileName = DateTime.Now.ToString("u");
                            fileName = Regex.Replace(fileName, "[\\W]", String.Empty, RegexOptions.Compiled);
                        }
                        fileName = Path.Combine(p, (fileName + ".xml"));
                        if (!(String.IsNullOrEmpty(Convert.ToString(v.NewValue))))
                        {
                            XmlWriterSettings settings = new XmlWriterSettings();
                            settings.CloseOutput = true;
                            XmlWriter writer = XmlWriter.Create(new FileStream(fileName, FileMode.Create), settings);
                            try
                            {
                                writer.WriteStartElement("note");
                                writer.WriteAttributeString("timestamp", DateTime.Now.ToString("o"));
                                writer.WriteAttributeString("username", HttpContext.Current.User.Identity.Name);
                                //MembershipUser user = Membership.GetUser();
                                if (SessionCache.CurrentUser == null)
                                {
                                    WebUtil.LoginUser();
                                }
                                User user = SessionCache.CurrentUser;
                                if (user == null)
                                {
                                    user = new User();
                                }

                                if (String.IsNullOrEmpty(user.Email))
                                {
                                    user.Email = "*****@*****.**";
                                }

                                writer.WriteAttributeString("email", user.Email);
                                writer.WriteString(Convert.ToString(v.NewValue));
                                writer.WriteEndElement();
                            }
                            finally
                            {
                                writer.Close();
                            }
                        }
                        else
                        {
                            File.Delete(fileName);
                            if (Directory.GetFiles(p).Length == 0)
                            {
                                Directory.Delete(p);
                            }
                        }
                    }
                }
            }
        }
Example #9
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);
        }
Example #10
0
        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;
                            }
                        }
                    }
                }
            }
        }