Beispiel #1
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);
        }
Beispiel #2
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());
        }