Ejemplo n.º 1
0
        /// <summary>
        /// </summary>
        /// <param name="DocSrc"></param>
        /// <param name="DocKeysFromDocId"></param>
        /// <param name="DocTypeName"></param>
        /// <param name="DocKeys">have precedence over DocId when is not null</param>
        /// <param name="DocId"></param>
        /// <param name="RelayUrl"></param>
        /// <returns></returns>
        public object Get(out string DocSrc, out Dictionary <string, string> DocKeysFromDocId, string DocTypeName, Dictionary <string, string> DocKeys = null, string DocId = null, string RelayUrl = null)
        {
            DocSrc           = null;
            DocKeysFromDocId = new Dictionary <string, string>();
            BaseDoc _BaseDoc = null;
            Dictionary <string, List <string> > _RequiredDocKeys = new Dictionary <string, List <string> >();

            DocKeys = DocKeys ?? DocKey.DocIdToKeys(DocId);

            foreach (KeyValuePair <string, string> _Item in DocKeys)
            {
                _RequiredDocKeys[_Item.Key] = new List <string> {
                    _Item.Value
                }
            }
            ;

            //BUG:DocStatus is not persisted by in the DocData; this band-aid gets it from the LightDoc in order to return it to the calling DataContract method
            foreach (Document _Document in ListDocuments(new List <string> {
                DocTypeName
            }, _RequiredDocKeys, null, null, 1, 0, RelayUrl, DirectoryPath))
            {
                _BaseDoc = DocInterpreter.Instance.Read(_Document.AsDocSubmissions().Last().Value);
                if (_BaseDoc.DocIdKeys.Count == DocKeys.Count)
                {
                    DocSrc           = Nav.ToUrl(DocTypeName, DocId, RelayUrl);
                    DocKeysFromDocId = _BaseDoc.DocIdKeys;
                    // there is a chance the DocStatus may not be set when it comes to items like DOCREV BaseDocType(s)
                    _BaseDoc.DocStatus = bool.Parse(_Document.Get(Parm.DocStatus) ?? Boolean.FalseString);
                    break;
                }
            }

            return(_BaseDoc);
        }
Ejemplo n.º 2
0
        private Document GetDoc(out string DocSrc, string DocTypeName, string DocId = null, string RelayUrl = null, string IndexDirectory = null)
        {
            Dictionary <string, List <string> > _RequiredDocKeys = new Dictionary <string, List <string> >();

            foreach (KeyValuePair <string, string> _Item in DocKey.DocIdToKeys(DocId))
            {
                _RequiredDocKeys[_Item.Key] = new List <string>
                {
                    _Item.Value
                }
            }
            ;

            //TODO:GetDoc needs to query by the exact key, not that a subset of DocKeys exist
            Document _Document = ListDocuments(new List <string>
            {
                DocTypeName
            },
                                               _RequiredDocKeys,
                                               null,
                                               null,
                                               1,
                                               0,
                                               RelayUrl,
                                               IndexDirectory).FirstOrDefault();

            DocSrc = _Document == null
                         ? null
                         : Nav.ToUrl(DocTypeName,
                                     DocId,
                                     RelayUrl);

            return(_Document);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Similar to Entity Framework Code First in concept, produce content files given a csharp object that represents the
        ///     doc type.
        /// </summary>
        /// <param name="baseDoc"></param>
        /// <param name="directoryInfo">
        ///     The folder these files will be written to if any content "merging" logic needs to take
        ///     place.
        /// </param>
        /// <returns>Relative filename path/name items & content</returns>
        public Dictionary <string, string> ContentFiles(BaseDoc baseDoc, DirectoryInfo directoryInfo)
        {
            string   solutionVersion = baseDoc.solutionVersion;
            FileInfo _ExistingTemplateJsonFileInfo = new FileInfo(string.Format(@"{0}\template.json", directoryInfo.FullName));

            // if there is an existing template.js the developer created, try to use as much of it as we can to write a new template.json that will accommodate the properties of the baseDoc passed
            string _TemplateJson = _ExistingTemplateJsonFileInfo.Exists
                                       ? File.ReadAllText(_ExistingTemplateJsonFileInfo.FullName)
                                       : _Interpreter.Write(new Rand().obj(baseDoc, "template.json"));

            //strip away any properties that may not be compatible datatype-wise with previous version of template.js & the new object
            string tempalte_json = _Interpreter.WritePI(
                _Interpreter.Write(
                    (BaseDoc)JsonConvert.DeserializeObject(
                        _TemplateJson,
                        baseDoc.GetType(),
                        new JsonSerializerSettings {
                Error = (o, args) => { args.ErrorContext.Handled = true; }
            })),
                new DocProcessingInstructions
            {
                DocChecksum     = 8678309,
                DocTypeName     = baseDoc.GetType().Name,
                solutionVersion = solutionVersion,
                DocTitle        = string.Format("{0} {1}, Base Line Data", baseDoc.DocTypeName, baseDoc.solutionVersion),
                DocId           = DocKey.DocIdFromKeys(
                    new Dictionary <string, string>
                {
                    { "DocTitle", baseDoc.DocTitle },
                    { "DocTypeName", baseDoc.DocTypeName },
                    { "solutionVersion", baseDoc.solutionVersion }
                })
            });


            Dictionary <string, string> _Dictionary = new Dictionary <string, string>
            {
                {
                    "template.json", tempalte_json
                },
                {
                    "default.htm", "<!-- TODO: add example code that could generically bind to the template.json to as an example -->"
                },
                {
                    "readme.txt", "TODO: add overview & links to resources"
                }
            };


            string[] files = Directory
                             .EnumerateFiles(directoryInfo.FullName, "*.*", SearchOption.AllDirectories)
                             .Union(_Dictionary.Keys)
                             .Select(m => string.Format("/{0}", m.Replace(directoryInfo.FullName, string.Empty).Replace("\\", "/").TrimStart('/', '\\')))
                             .Distinct()
                             .OrderBy(m => m)
                             .ToArray();

            File.WriteAllText(_ExistingTemplateJsonFileInfo.FullName, tempalte_json);
            return(_Dictionary);
        }
Ejemplo n.º 4
0
        private void btnSeleccionar_Click(object sender, EventArgs e)
        {
            if (IdDocumento == -3)
            {
                string var = string.Empty;

                foreach (var item in dgvDatos.Selected.Rows)
                {
                    var = Convert.ToString(item.Cells["DocEntry"].Value);
                    DocKey.Add(var);
                }

                this.DialogResult = System.Windows.Forms.DialogResult.Yes;
            }
            else if (IdDocumento == -2 | IdDocumento == -6 | IdDocumento == -8)
            {
                foreach (var item in dgvDatos.Selected.Rows)
                {
                    DocKeys ojb = new DocKeys();

                    ojb.DocEntry = Convert.ToString(item.Cells["DocEntry"].Value);
                    ojb.DocType  = Convert.ToString(item.Cells["ObjType"].Value);
                    seleccionados.Add(ojb);
                }

                this.DialogResult = System.Windows.Forms.DialogResult.Yes;
            }
        }
Ejemplo n.º 5
0
        private void dgvDatos_DoubleClickCell(object sender, Infragistics.Win.UltraWinGrid.DoubleClickCellEventArgs e)
        {
            try
            {
                if (IdDocumento == 1 || IdDocumento == 10008 || IdDocumento == 10009)
                {
                    if (IdDocumento == 1)
                    {
                        Tipo = Convert.ToString(dgvDatos.Rows[e.Cell.Row.Index].Cells["Tipo"].Value);
                    }

                    DocEntry = Convert.ToInt32(dgvDatos.Rows[e.Cell.Row.Index].Cells["Número de documento"].Value);

                    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                }
                if (IdDocumento == 8 || IdDocumento == 9)
                {
                    DocEntry = Convert.ToInt32(dgvDatos.Rows[e.Cell.Row.Index].Cells["Número de documento"].Value);
                    Tipo     = Convert.ToString(dgvDatos.Rows[e.Cell.Row.Index].Cells["Doc"].Value);

                    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                }
                else if (IdDocumento == -1 | IdDocumento == -5 | IdDocumento == -7)
                {
                    string var = string.Empty;
                    var = Convert.ToString(dgvDatos.Rows[e.Cell.Row.Index].Cells["CardCode"].Value);

                    DocKey.Add(var);

                    Row = (from item in source.AsEnumerable()
                           where item.Field <string>("CardCode").Equals(var)
                           select item).FirstOrDefault();

                    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                }
                else if (IdDocumento == -2 | IdDocumento == -3 | IdDocumento == -6 | IdDocumento == -8)
                {
                    string var = string.Empty;

                    // dgvDatos.Selected.

                    //foreach (var item in dgvDatos.Selected.Rows)
                    //{
                    var = Convert.ToString(dgvDatos.ActiveRow.Cells["DocEntry"].Value);
                    DocKey.Add(var);
                    //}

                    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                }
                else if (IdDocumento == -4)
                {
                    ItemCode = Convert.ToString(dgvDatos.ActiveRow.Cells[0].Value);

                    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 6
0
        private void Submit_Internal(string DocData, string DocSubmittedBy, string RelayUrl = null, bool?DocStatus = null, DateTime?SubmittedDate = null, Dictionary <string, string> DocKeys = null, string DocTitle = null)
        {
            DocData = BaseController.PIRewrite(DocData, DocStatus, SubmittedDate, DocKeys, DocTitle, DocSubmittedBy);

            // let the BaseDoc parse it's string just as normal
            BaseDoc _SubmittedBaseDoc = DocInterpreter.Instance.Read(DocData, true);
            Type    _SqlBaseDocType   = ReverseEngineerCodeFirst(_SubmittedBaseDoc);

            BaseDoc _SqlBaseDoc = (BaseDoc)Activator.CreateInstance(_SqlBaseDocType);

            IQueryable _SqlList = ListInternal(_SqlBaseDocType, _SubmittedBaseDoc.DocIdKeys.ToNameValueCollection()).AsQueryable();

            if (_SqlList.Any())
            {
                foreach (var o in _SqlList)
                {
                    _SqlBaseDoc = (BaseDoc)o;
                }
            }

            if (_SqlBaseDoc.DocChecksum != _SubmittedBaseDoc.DocChecksum)
            {
                JObject _SubmittedJObject = JObject.FromObject(_SubmittedBaseDoc, _JsonSerializer);

                if (_SqlBaseDoc.Id > 0)
                {
                    // Serialize the _ExistingBaseDoc Id property values only (the rest of the values will be merged in from the _SubmittedBaseDoc)
                    // keep in mind that EF lazy loading will kick in & load to ensure all the child objects & there Id(s) are serialized here
                    string  _SqlIdsAsJson = JsonConvert.SerializeObject(_SqlBaseDoc, SqlIdsOnlySerializeContractResolver.MyJsonSerializerSettings);
                    JObject _SqlJObject   = JObject.Parse(_SqlIdsAsJson);

                    // take the SQL Id(s) from the existing data & the new textual content from the new submission & combine them
                    // in order to make a clean up to the SQL database
                    _SubmittedJObject.Merge(_SqlJObject, _JsonMergeSettings);

                    _SqlBaseDoc = (BaseDoc)JsonConvert.DeserializeObject(
                        _SubmittedJObject.ToString(),
                        _SqlBaseDoc.GetType(),
                        TextualShouldSerializeContractResolver.MyJsonSerializerSettings);

                    // Utilize PropertyOverlay.Overlay(topO,bottomO,true), set those combined objects of business data & SQL Ids to the _ExistingBaseDoc
                    // ensure the PropertyOverlay.Overlay sizeToTop is set to true in order to force child List item counts (one-to-many) to agree with
                    // what the user has submitted. This results in Insert/Update/Delete statements shaping the existing dataset (_ExistingBaseDoc)
                    // to the _SubmittedBaseDoc.
                }
                else
                {
                    _SqlBaseDoc = (BaseDoc)JsonConvert.DeserializeObject(
                        _SubmittedJObject.ToString(),
                        _SqlBaseDoc.GetType(),
                        TextualShouldSerializeContractResolver.MyJsonSerializerSettings);

                    MetaTable _docKeyTable = GetDocKeyTable(_SqlBaseDoc);
                    foreach (KeyValuePair <string, string> _Item in _SubmittedBaseDoc.DocIdKeys)
                    {
                        DocKey _DocKeyEntry = (DocKey)Activator.CreateInstance(_docKeyTable.EntityType, null);
                        _DocKeyEntry.Id      = _SqlBaseDoc.Id;
                        _DocKeyEntry.KeyName = _Item.Key;
                        _DocKeyEntry.KeyVal  = _Item.Value;
                        SqlDB.GetInstance(_SqlBaseDoc).UnderlyingDbContext.Set(_docKeyTable.EntityType).Add(_DocKeyEntry);
                    }
                }
                _SqlBaseDoc.Save();
            }
        }
Ejemplo n.º 7
0
        private IEnumerable ListInternal(BaseDoc filter, NameValueCollection docKeyFilters = null, int PageSize = 150, int PageIndex = 0)
        {
            docKeyFilters = docKeyFilters ?? new NameValueCollection();
            string propInfoPredicate = string.Empty;

            //TODO:Add logic to filter forms based on the documentKey(s) passed
            Dictionary <string, string> DocKeys = filter.DocIdKeys;

            foreach (string key in filter.DocIdKeys.Keys)
            {
                docKeyFilters.Add(key, DocKeys[key]);
            }

            foreach (string key in DocKeys.Keys)
            {
                docKeyFilters.Add(key, DocKeys[key]);
            }

            filter.DocId = null;

            // predicate formed from PropertyInfo[] of the form business object
            // FormHandlerNavigation filterFormHandlerNavigation = new FormHandlerNavigation(filter);
            // List<object> parms =  filterFormHandlerNavigation.RenderNavigateUrlParameters().ToList<object>();
            List <object> parms = new List <object>();
            StringBuilder predicateStringBuilder = new StringBuilder();
            MetaTable     _table = GetFormTable(filter);

            // run through all the properties suitable for SQL/EF-mapping
            foreach (PropertyInfo _PropertyInfo in filter.GetFormObjectNavProperties(true).Where(m => !Attribute.IsDefined(m, typeof(NotMappedAttribute))))
            {
                Type parmType   = ExpressionParser.GetNonNullableType(_PropertyInfo.PropertyType) ?? _PropertyInfo.PropertyType;
                bool IsNullable = parmType != _PropertyInfo.PropertyType;
                parms.Add(Convert.ChangeType(_PropertyInfo.GetValue(filter, null), parmType, null));

                bool Null_Value = false;
                if (!Null_Value)
                {
                    Null_Value = IsNullable && parmType.IsPrimitive;
                }
                if (!Null_Value)
                {
                    Null_Value = IsNullable && parmType == typeof(DateTime);
                }

                predicateStringBuilder
                .Append(_PropertyInfo.Name)
                .Append(Null_Value ? ".Value" : string.Empty)
                .Append(".Equals(@")
                .Append(parms.Count - 1)
                .Append(") && ");
            }

            propInfoPredicate = predicateStringBuilder.ToString().Trim(' ', '&');

            // Merge the docKeys & NameValueCollection items
            // Remove dictionary items that exist in the namevalue collection first
            MetaTable     _docKeyTable            = GetDocKeyTable(filter);
            StringBuilder DocKeyMatchSQLPredicate = new StringBuilder();

            foreach (string key in docKeyFilters.Keys)
            {
                DocKeyMatchSQLPredicate
                .AppendFormat(@" OR  ( N'{0}' = KeyName  AND  ( ", key)
                .Append(string.Join(" or ", docKeyFilters.GetValues(key).Select(m => "N'" + m + "'=Keyval").Distinct().ToArray()))
                .Append(") )");
            }

            /* note this reference to CamelCase is also done in the .tt file to make the SQL column names pretty.
             * technically we should be reading the properties Column attribute value to get the CamelCase
             * version of the property's name */
            string docKeyMatchSQL = "";

            docKeyMatchSQL = docKeyFilters.Count == 0
                                 ? string.Empty
                                 : string.Format(
                @"
        
                    SELECT TOP 1 Id
                    FROM   {1}.{2} /* The docKey table for the given entity */
                    WHERE  {3} /* The predicate */
                    GROUP  BY Id HAVING COUNT(*) = {4}",
                "Id",
                string.IsNullOrWhiteSpace(propInfoPredicate)
                                         ? filter.DocTypeName
                                         : "(" + ((ObjectQuery)_table.GetQuery().Where(propInfoPredicate, parms.ToArray())).ToTraceString() + ")", /* Notice we use the MetaTable that has access to the underlying ObjectContext to yield our object-SQL */
                _docKeyTable.Name,
                DocKeyMatchSQLPredicate.ToString().Replace(" OR ", " || ").Trim(' ', '|').Replace(" || ", " OR "),
                docKeyFilters.Keys.Count);


            // locate the keys
            object[] keyValues = !string.IsNullOrWhiteSpace(docKeyMatchSQL)
                                     ? SqlDB.GetInstance(filter).UnderlyingDbContext.Database.SqlQuery <int>(docKeyMatchSQL).Cast <object>().ToArray()
                                     : new object[]
            {};

            filter.DocId = DocKey.DocIdFromKeys(DocKeys);

            return(!string.IsNullOrWhiteSpace(docKeyMatchSQL)
                       ? keyValues.Length == 0
                             ? new List <object>() : new List <object>
            {
                SqlDB.GetInstance(filter).UnderlyingDbContext.Set(_table.EntityType).Find(keyValues)
            }
                       : !string.IsNullOrWhiteSpace(propInfoPredicate)
                             ? (IEnumerable)_table.GetQuery().Where(propInfoPredicate, parms.ToArray()).Skip(PageIndex).Take(PageSize)
                             : new List <BaseDoc>().AsEnumerable());
        }
Ejemplo n.º 8
0
        /**************************************************************************/

        private void RenderListView(Dictionary <ulong, bool> History, MacroscopeDocumentCollection DocCollection)
        {
            if (History.Count == 0)
            {
                return;
            }

            List <ListViewItem> ListViewItems = new List <ListViewItem>(1);

            MacroscopeAllowedHosts AllowedHosts = this.MainForm.GetJobMaster().GetAllowedHosts();
            MacroscopeSinglePercentageProgressForm ProgressForm = new MacroscopeSinglePercentageProgressForm(this.MainForm);
            decimal Count           = 0;
            decimal TotalDocs       = (decimal)History.Count;
            decimal MajorPercentage = ((decimal)100 / TotalDocs) * Count;

            if (MacroscopePreferencesManager.GetShowProgressDialogues())
            {
                ProgressForm.UpdatePercentages(
                    Title: "Preparing Display",
                    Message: "Processing document collection for display:",
                    MajorPercentage: MajorPercentage,
                    ProgressLabelMajor: string.Format("Document {0} / {1}", Count, TotalDocs)
                    );
            }

            foreach (ulong DocKey in History.Keys)
            {
                ListViewItem       lvItem  = null;
                MacroscopeDocument msDoc   = DocCollection.GetDocumentByDocKey(DocKey: DocKey);
                string             PairKey = DocKey.ToString();

                if (msDoc != null)
                {
                    string Url             = msDoc.GetUrl();
                    string Visited         = "No";
                    string InDocCollection = "No";

                    if (History.ContainsKey(DocKey) && History[DocKey])
                    {
                        Visited = "Yes";
                    }

                    if (DocCollection.ContainsDocument(Url: Url))
                    {
                        InDocCollection = "Yes";
                    }

                    if (this.DisplayListView.Items.ContainsKey(PairKey))
                    {
                        try
                        {
                            lvItem = this.DisplayListView.Items[PairKey];
                            lvItem.SubItems[ColUrl].Text             = Url;
                            lvItem.SubItems[ColVisited].Text         = Visited;
                            lvItem.SubItems[ColInDocCollection].Text = InDocCollection;
                        }
                        catch (Exception ex)
                        {
                            DebugMsg(string.Format("RenderListView 1: {0}", ex.Message));
                        }
                    }
                    else
                    {
                        try
                        {
                            lvItem = new ListViewItem(PairKey);
                            lvItem.UseItemStyleForSubItems = false;

                            lvItem.Name = PairKey;

                            lvItem.SubItems[0].Text = Url;
                            lvItem.SubItems.Add(Visited);
                            lvItem.SubItems.Add(InDocCollection);

                            ListViewItems.Add(lvItem);
                        }
                        catch (Exception ex)
                        {
                            DebugMsg(string.Format("RenderListView 2: {0}", ex.Message));
                        }
                    }

                    if (lvItem != null)
                    {
                        lvItem.ForeColor = Color.Blue;

                        if (AllowedHosts.IsInternalUrl(Url))
                        {
                            lvItem.SubItems[ColUrl].ForeColor = Color.Green;
                            if (History.ContainsKey(DocKey) && History[DocKey])
                            {
                                lvItem.SubItems[ColVisited].ForeColor = Color.Green;
                            }
                            else
                            {
                                lvItem.SubItems[ColVisited].ForeColor = Color.Red;
                            }
                            lvItem.SubItems[ColInDocCollection].ForeColor = Color.Blue;
                        }
                        else
                        {
                            lvItem.SubItems[ColUrl].ForeColor             = Color.Gray;
                            lvItem.SubItems[ColVisited].ForeColor         = Color.Gray;
                            lvItem.SubItems[ColInDocCollection].ForeColor = Color.Gray;
                        }
                    }
                }

                if (MacroscopePreferencesManager.GetShowProgressDialogues())
                {
                    Count++;
                    TotalDocs       = (decimal)History.Count;
                    MajorPercentage = ((decimal)100 / TotalDocs) * Count;

                    ProgressForm.UpdatePercentages(
                        Title: null,
                        Message: null,
                        MajorPercentage: MajorPercentage,
                        ProgressLabelMajor: string.Format("Document {0} / {1}", Count, TotalDocs)
                        );
                }
            }

            this.DisplayListView.Items.AddRange(ListViewItems.ToArray());

            if (MacroscopePreferencesManager.GetShowProgressDialogues())
            {
                ProgressForm.DoClose();
            }

            if (ProgressForm != null)
            {
                ProgressForm.Dispose();
            }
        }
Ejemplo n.º 9
0
 public bool MatchDocKeyName(string testDocKey)
 {
     return(HasDocKey &&
            DocKey.Equals(testDocKey));
 }