Exemplo n.º 1
0
        /// <summary>
        ///     Expects the directory to contain an infopath manifest.xsf & template.xml files. The contents are then persisted &
        ///     indexed by DocTypeName & DocTypeRev (aka solutionVersion) for OpenStream & OpenText operations. As of this writing,
        ///     this application must have write access to the parent folder of the given directory for cab compression operations.
        /// </summary>
        /// <param name="importFolderPath"></param>
        /// <param name="workingFolderPath">default is parent of importFolderPath</param>
        public static List <ImporterLightDoc> ImportContentFolder(string sourceFolderPath, string workingFolderPath = null)
        {
            List <ImporterLightDoc> List_ImporterLightDoc = new List <ImporterLightDoc>();

            DirectoryInfo _DirectoryInfo = new DirectoryInfo(sourceFolderPath);

            if (workingFolderPath == null)
            {
                workingFolderPath = RequestPaths.GetPhysicalApplicationPath(Resources.import_DirectoryPath);
            }

            //// ensure the import folder actually exists
            new DirectoryInfo(workingFolderPath)
            .mkdir()
            .Attributes = FileAttributes.NotContentIndexed | FileAttributes.Hidden;

            string DocMD5, DocTypeVer;
            string DocTypeName = FilesystemTemplateController.ScanContentFolder(_DirectoryInfo, out DocTypeVer, out DocMD5);

            if (!DocExchange.LuceneController.List(new List <string> {
                EmbededInterpreter.MY_ONLY_DOC_NAME
            }, null, null, DocMD5).Any())
            {
                IList <string> relativeFilePathsInDirectoryTree = GetRelativeFilePathsInDirectoryTree(_DirectoryInfo.FullName, true);
                IDictionary <string, string> files = CreateStringDictionary(relativeFilePathsInDirectoryTree, relativeFilePathsInDirectoryTree);
                IDocRev DocRevBaseDoc = (IDocRev)DocInterpreter.Instance.Create(EmbededInterpreter.MY_ONLY_DOC_NAME);

                DocRevBaseDoc.Target.DocTypeName     = DocTypeName;
                DocRevBaseDoc.Target.solutionVersion = DocTypeVer;
                DocRevBaseDoc.DocChecksum            = int.MinValue;
                DocRevBaseDoc.DocStatus   = true;
                DocRevBaseDoc.DocTitle    = String.Format("{0} {1}", DocTypeName, DocTypeVer);
                DocRevBaseDoc.DocTypeName = EmbededInterpreter.MY_ONLY_DOC_NAME;
                DocRevBaseDoc.MD5         = DocMD5;
                DocRevBaseDoc.DocKeys     = new Dictionary <string, string>
                {
                    { Properties.Resources.TargetDocTypeNameKey, DocTypeName },
                    { Properties.Resources.TargetDocTypeVerKey, DocTypeVer }
                };

                foreach (KeyValuePair <string, string> file in files)
                {
                    FileInfo AddFileInfo = new FileInfo(_DirectoryInfo.FullName + "\\" + file.Value);
                    DocRevBaseDoc.FileList.Add(
                        new DocRevEntry()
                    {
                        Bytes = AddFileInfo.OpenRead().AsBytes(),
                        Name  = file.Key
                    });
                }

                List_ImporterLightDoc.Add(
                    new ImporterLightDoc
                {
                    LightDoc = DocExchange.Instance.Import(
                        DocInterpreter.Instance.WriteStream((BaseDoc)DocRevBaseDoc))
                });
            }
            return(List_ImporterLightDoc);
        }
Exemplo n.º 2
0
        /// <summary>
        /// </summary>
        /// <returns>null if not a master calling</returns>
        protected T Slave()
        {
            if (!isMaster())
            {
                return(null);
            }
            lock (_Slave)
            {
                string exeAssembly = GetType().Assembly.FullName;

                if (_MySlaveAppDomain == null)
                {
                    // Construct and initialize settings for a second AppDomain.
                    AppDomainSetup _AppDomainSetup = new AppDomainSetup
                    {
                        ApplicationBase          = new Uri(RequestPaths.GetPhysicalApplicationPath()).ToString(),
                        DisallowBindingRedirects = false,
                        DisallowCodeDownload     = false,
                        ConfigurationFile        = new Uri(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).ToString(),
                        ApplicationName          = SlaveAppDomainFriendlyName(),
                        PrivateBinPathProbe      = new Uri(Directory.Exists(RequestPaths.GetPhysicalApplicationPath("bin"))
                                                          ? RequestPaths.GetPhysicalApplicationPath("bin")
                                                          : Path.GetDirectoryName(GetType().Assembly.Location)).ToString(),
                        PrivateBinPath = new Uri(Directory.Exists(RequestPaths.GetPhysicalApplicationPath("bin"))
                                                     ? RequestPaths.GetPhysicalApplicationPath("bin")
                                                     : Path.GetDirectoryName(GetType().Assembly.Location)).ToString()
                    };

                    // Create the second AppDomain.
                    _MySlaveAppDomain = AppDomain.CreateDomain(SlaveAppDomainFriendlyName(), null, _AppDomainSetup);
                }

                return((T)_MySlaveAppDomain.CreateInstanceAndUnwrap(exeAssembly, typeof(T).FullName));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Attempts to get the dCForm web service URL from an appsetting set explicitly in the MyName folder
        ///     or by looking for a web service entry in the application main web.config
        /// </summary>
        /// <returns></returns>
        private static string ResolveFormHandlerUrl()
        {
            if (string.IsNullOrWhiteSpace(FormHandlerUrl))
            {
                // try parse from explicit set in the MyName\web.config
                if (string.IsNullOrWhiteSpace(FormHandlerUrl))
                {
                    FormHandlerUrl = string.Format("{0}", ConfigurationManager.AppSettings["ServiceUrl"]);
                }

                // try parse from WCF service address in the App root by search for something that references IPB.svc

                string webconfigXml = File.ReadAllText(RequestPaths.GetPhysicalApplicationPath("web.config"));
                if (string.IsNullOrWhiteSpace(FormHandlerUrl))
                {
                    FormHandlerUrl = string.Format("{0}", FormHandlerUrlParse.Match(webconfigXml).Value);
                }


                // make sure the URL is pretty and escaped
                if (!string.IsNullOrWhiteSpace(FormHandlerUrl))
                {
                    // are we dealing with a file?
                    if (FormHandlerUrl.LastIndexOf('.') > FormHandlerUrl.LastIndexOf('/'))
                    {
                        FormHandlerUrl = new Uri(FormHandlerUrl.Substring(0, FormHandlerUrl.LastIndexOf("/") - 1), UriKind.RelativeOrAbsolute).ToString();
                    }
                }
            }

            return(FormHandlerUrl);
        }
 /// <summary>
 ///     Sets up the form directory if not there. New or not, all read-only file attributes are removed from sub-folders &
 ///     files
 /// </summary>
 static FilesystemTemplateController()
 {
     DirectoryPath = RequestPaths.GetPhysicalApplicationPath("doc");
     //Task.Factory.StartNew(() =>
     //                      {
     new DirectoryInfo(DirectoryPath)
     .mkdir()
     .rAttrib(FileAttributes.NotContentIndexed);
     //});
 }
Exemplo n.º 5
0
        /// <summary>
        /// </summary>
        /// <param name="_DocDirectoryInfo"></param>
        /// <param name="DocTypeName"></param>
        /// <param name="DocProperties"></param>
        /// <param name="DocRev"></param>
        /// <returns>TODO:Needs to return a DocRev & not write files to a physical directory</returns>
        public static BaseDoc Templify(string DocTypeName, List <CompositeProperty> DocProperties, string DocRev = null)
        {
            DirectoryInfo _DocDirectoryInfo =
                new DirectoryInfo(FilesystemTemplateController.GetDocDirectoryPath(DocTypeName)).mkdir();

            if (string.IsNullOrWhiteSpace(DocRev))
            {
                DocRev = DateTime.UtcNow.AsDocRev();
            }

            string temporaryNamespace  = RuntimeTypeNamer.CalcCSharpNamespace(DocTypeName, DocRev, typeof(DocTempleter).Name);
            string cSharpClassFullName = RuntimeTypeNamer.CalcCSharpNamespace(DocTypeName, DocRev);

            FileInfo _XsdFileInfo        = new FileInfo(String.Format(@"{0}\{1}", _DocDirectoryInfo.FullName, Runtime.MYSCHEMA_XSD_FILE_NAME));
            Type     _template_docx_type = new CompositeType(temporaryNamespace, _DocDirectoryInfo.Name, DocProperties.ToArray());

            // the "lazy-load" CompositeType requires activation in order for the _template_docx_obj.GetType().Assembly to register as having any types defined
            object _template_docx_obj = Activator.CreateInstance(_template_docx_type);

            string xsd = XsdExporter.ExportSchemas(
                _template_docx_obj.GetType().Assembly,
                new List <string> {
                DocTypeName
            },
                RuntimeTypeNamer.CalcSchemaUri(DocTypeName, DocRev)).First();

            File.WriteAllText(_XsdFileInfo.FullName, xsd, Encoding.Unicode);

            string myclasses_cs = new Xsd().ImportSchemasAsClasses(
                new[] { xsd },
                cSharpClassFullName,
                CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateProperties,
                new StringCollection());

            myclasses_cs = Runtime.CustomizeXsdToCSharpOutput(DocTypeName, myclasses_cs, null, new[] { nameof(IDocModel) });

            if (Directory.Exists(RequestPaths.GetPhysicalApplicationPath(Resources.App_Code_DirectoryPath)))
            {
                File.WriteAllText(RequestPaths.GetPhysicalApplicationPath(Resources.App_Code_DirectoryPath, DocTypeName + ".cs"), myclasses_cs, Encoding.Unicode);
            }
            else
            {
                File.WriteAllText(_DocDirectoryInfo.FullName + @"\\example.cs", myclasses_cs, Encoding.Unicode);
            }

            BaseDoc _BaseDoc = Runtime.FindBaseDoc(Runtime.CompileCSharpCode(myclasses_cs), DocTypeName);

            // reset the values critical to this import that were implicitly set by the Rand()
            _BaseDoc.solutionVersion = DocRev;
            _BaseDoc.DocTypeName     = DocTypeName;
            _BaseDoc.href            = String.Empty;

            return(_BaseDoc);
        }
Exemplo n.º 6
0
        /// <summary>
        ///     first response performance critical
        /// </summary>
        /// <returns></returns>
        public override MetadataSet GetGeneratedMetadata()
        {
            ImporterController.TryDocRevImporting();

            int i = 0;
            // let the base build up metadata for the service contracts as these are static
            MetadataSet _MetadataSet = base.GetGeneratedMetadata();

            foreach (DirectoryInfo _DirectoryInfo in Directory
                     .EnumerateDirectories(FilesystemTemplateController.DirectoryPath)
                     .Select(path => new DirectoryInfo(path)))
            {
                // persist the datacontract xml schema for the datacontract to the user's temporary directory
                //TODO:combine this logic and Runtime's that calculates it's dll output location
                int key = Math.Abs(File.ReadAllText(
                                       RequestPaths.GetPhysicalApplicationPath(
                                           "doc",
                                           _DirectoryInfo.Name,
                                           Runtime.MYSCHEMA_XSD_FILE_NAME)).GetHashCode()
                                   ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode()); // just incase the user changes due to an apppool change

                string tempDataContractXsdPath = string.Format("{0}\\{1}.xsd", Path.GetTempPath(), Base36.Encode(key));

                if (!File.Exists(tempDataContractXsdPath))
                {
                    // the datacontracts are the things that are dynamic & change according to what DocTypes are present
                    XsdDataContractExporter _XsdDataContractExporter = new XsdDataContractExporter();
                    Type DocType = Runtime.ActivateBaseDocType(_DirectoryInfo.Name, TemplateController.Instance.TopDocRev(_DirectoryInfo.Name));
                    _XsdDataContractExporter.Export(DocType);
                    // _XsdDataContractExporter.Schemas.CompilationSettings.EnableUpaCheck = true;
                    _XsdDataContractExporter.Schemas.Compile();

                    foreach (XmlSchema _XmlSchema in _XsdDataContractExporter.Schemas.Schemas(_XsdDataContractExporter.GetRootElementName(DocType).Namespace))
                    {
                        using (Stream _Stream = File.OpenWrite(tempDataContractXsdPath))
                        {
                            _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(_XmlSchema));
                            _XmlSchema.Write(_Stream);
                            break;
                        }
                    }
                }

                using (Stream _Stream = File.OpenRead(tempDataContractXsdPath))
                    _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(
                                                          XmlSchema.Read(_Stream, (s, o) =>
                    {
                        /*if (o != null && o.Exception != null) throw o.Exception;*/
                    })));
            }

            return(_MetadataSet);
        }
Exemplo n.º 7
0
        private bool CreateNeeded()
        {
            DirectoryPath = RequestPaths.GetPhysicalApplicationPath("App_Data\\nosql");

            // ensure the import folder actually exists
            if (!Directory.Exists(DirectoryPath))
            {
                new DirectoryInfo(DirectoryPath)
                .mkdir()
                .Attributes = FileAttributes.NotContentIndexed | FileAttributes.Hidden;
                return(true);
            }

            return(!Directory.EnumerateFiles(DirectoryPath).Any());
        }
Exemplo n.º 8
0
        /// <summary>
        ///     When operating on the client, a search is performed on the ~/MyName/web.config
        ///     & the configuration is read or path is assumed simply by the ~/MyName. At this time, only http(s) protocols are
        ///     supported.
        /// </summary>
        /// <returns></returns>
        internal static string GetRelayUrl()
        {
            if (_GetRelayUrlFound == string.Empty)
            {
                if (File.Exists(RequestPaths.GetPhysicalApplicationPath(DirectoryName, "web.config")))
                {
                    string path = string.Format("{0}/{1}", RequestPaths.ApplicationPath, DirectoryName);
                    if (path.ToLower().StartsWith("http"))
                    {
                        _GetRelayUrlFound = path;
                    }
                }
            }

            // one last effort to
            return(_GetRelayUrlFound);
        }
Exemplo n.º 9
0
        public static Assembly CompileCSharpCode(Func <string> cSharpCodeFactory, string OutputName = default(string))
        {
            // can't be null as it will be used in calc later
            OutputName = OutputName ?? string.Empty;

            string cSharpCode = string.IsNullOrWhiteSpace(OutputName)
                                    ? cSharpCodeFactory.Invoke()
                                    : string.Empty;

            bool IncludeDebugInformation =
#if DEBUG
                true;
#else
                false;
#endif
            int key = Math.Abs(cSharpCode.GetHashCode()
                               ^ OutputName.GetHashCode()
                               ^ IncludeDebugInformation.GetHashCode()
                               ^ typeof(Runtime).Assembly.FullName.GetHashCode()
                               ^ WindowsIdentity.GetCurrent()
                               .User.Value.GetHashCode()                  // just incase the user changes due to an apppool change
                               );

            if (!CompileCSharpCodeAssemblies.ContainsKey(key))
            {
                CompilerParameters _CompilerParameters = new CompilerParameters
                {
                    IncludeDebugInformation = IncludeDebugInformation,
                    GenerateExecutable      = false,
                    GenerateInMemory        = false,
                    WarningLevel            = 0,
                    TreatWarningsAsErrors   = false
                };

                // it was unknown at them time of this writing
                if (!string.IsNullOrWhiteSpace(CompileCSharpCodeDefaultOutDirectory))
                {
                    _CompilerParameters.OutputAssembly = string.Format(
                        "{0}\\{1}{2}.dll",
                        CompileCSharpCodeDefaultOutDirectory,
                        string.IsNullOrWhiteSpace(OutputName)
                            ? string.Empty
                            : string.Format("{0}.", FileSystem.CleanFileName(OutputName)),
                        Base36.Encode(key));

                    if (_CompilerParameters.OutputAssembly.Length > 250)
                    {
                        _CompilerParameters.OutputAssembly = string.Format("{0}\\{1}{2}.dll", CompileCSharpCodeDefaultOutDirectory, string.Empty, Base36.Encode(key));
                    }
                }

                if (File.Exists(_CompilerParameters.OutputAssembly))
                {
                    CompileCSharpCodeAssemblies[key] = Assembly.LoadFile(_CompilerParameters.OutputAssembly);
                }
                else
                {
                    // naming parts where specified above so the cSharpCode was no needed right away to calculate the base36 filename, now we actually need to cSharp code for it's primary purpose (to compile it)
                    if (string.IsNullOrWhiteSpace(cSharpCode))
                    {
                        cSharpCode = cSharpCodeFactory.Invoke();
                    }

                    lock (CSharpCodeProvider)
                    {
                        // Combine & normalize (different paths that load to the same dll) lists of referenced assemblies.
                        // Consider our custom list (UsingNamespaces.Values) & whatever is currently loaded into the AppDomain.
                        // This ensures the newly compiled object will have everything it needs.
                        Dictionary <string, string> ReferenceAssembliesDic = new Dictionary <string, string>();
                        foreach (string AppDomainAssemFileName in
                                 AppDomain.CurrentDomain.GetAssemblies()
                                 .Where(m => !m.IsDynamic)
                                 .Select(m => m.Location))
                        {
                            if (File.Exists(AppDomainAssemFileName))
                            {
                                foreach (
                                    string DirectoryName in
                                    new[] {
                                    new FileInfo(AppDomainAssemFileName).DirectoryName,
                                    @".",
                                    @".\bin",
                                    @".\bin\debug",
                                    @".\bin\release"
                                })
                                {
                                    if (Directory.Exists(DirectoryName))
                                    {
                                        foreach (FileInfo _FileInfo in USING_NAMESPACES
                                                 .Values
                                                 .Select(FileName => String.Format(@"{0}\\{1}", DirectoryName, FileName))
                                                 .Where(FilePath => File.Exists(FilePath))
                                                 .Select(FilePath => new FileInfo(FilePath))
                                                 .Where(_FileInfo => !ReferenceAssembliesDic.ContainsKey(_FileInfo.Name.ToLower())))
                                        {
                                            ReferenceAssembliesDic[_FileInfo.Name.ToLower()] = _FileInfo.FullName;
                                        }
                                    }
                                }
                            }
                        }

                        _CompilerParameters.ReferencedAssemblies.AddRange(ReferenceAssembliesDic.Values.ToArray());

                        CompilerResults _CompilerResults = CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                        if (_CompilerResults.Errors.Count == 0)
                        {
                            CompileCSharpCodeDefaultOutDirectory = Path.GetDirectoryName(_CompilerResults.PathToAssembly);
                            CompileCSharpCodeAssemblies[key]     = _CompilerResults.CompiledAssembly;
                        }
                        else
                        {
                            new DirectoryInfo(RequestPaths.GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES)).mkdir()
                            .Attributes = FileAttributes.Hidden;

                            int           i = 0;
                            DirectoryInfo _DirectoryInfo = null;

                            // often there are processes that just won't let there handles go off previous files generated
                            // now we try delete those directories or create a new one with an auto-incremented number when the previous can't be removed
                            do
                            {
                                _DirectoryInfo = new DirectoryInfo(
                                    RequestPaths
                                    .GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES, string.Format("{0}_{1}", Base36.Encode(key), i++)));

                                try
                                {
                                    _DirectoryInfo.rmdir();
                                }
                                catch (Exception) { }
                            }while (_DirectoryInfo.Exists);

                            _DirectoryInfo.mkdir();

                            _CompilerParameters.GenerateInMemory        = false;
                            _CompilerParameters.IncludeDebugInformation = true;
                            _CompilerParameters.TempFiles             = new TempFileCollection(_DirectoryInfo.FullName, true);
                            _CompilerParameters.TreatWarningsAsErrors = true;

                            CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                            throw new Exception(string.Format("\"{0}\" Contains runtime the intermediate files of a runtime build (compile) that failed.", _DirectoryInfo.FullName));
                        }
                    }
                }
            }
            return(CompileCSharpCodeAssemblies[key]);
        }
Exemplo n.º 10
0
        /// <summary>
        /// </summary>
        /// <param name="cSharpCode"></param>
        /// <param name="TempFileFolderName">Define this for debugging purposes</param>
        /// <returns></returns>
        internal static Assembly CompileCSharpCode(string cSharpCode, params string[] DebuggingTempFileDirectoryNameParts)
        {
            bool IncludeDebugInformation =
#if DEBUG
                true;
#else
                false;
#endif
            int key = Math.Abs(cSharpCode.GetHashCode()
                               ^ IncludeDebugInformation.GetHashCode()
                               ^ typeof(Runtime).Assembly.FullName.GetHashCode()
                               ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode() // just incase the user changes due to an apppool change
                               );

            if (!CompileCSharpCodeAssemblies.ContainsKey(key))
            {
                CompilerParameters _CompilerParameters = new CompilerParameters
                {
                    IncludeDebugInformation = IncludeDebugInformation,
                    GenerateExecutable      = false,
                    GenerateInMemory        = false,
                    WarningLevel            = 0
                };

                // it was unknown at them time of this writting
                if (!string.IsNullOrWhiteSpace(CompileCSharpCodeDefaultOutDirectory))
                {
                    _CompilerParameters.OutputAssembly = CompileCSharpCodeDefaultOutDirectory + "\\" + Base36.Encode(key) + ".dll";
                }

                if (File.Exists(_CompilerParameters.OutputAssembly))
                {
                    CompileCSharpCodeAssemblies[key] = Assembly.LoadFile(_CompilerParameters.OutputAssembly);
                }
                else
                {
                    // Combine & normalize (different paths that load to the same dll) lists of referenced assemblies. Consider our custom list (UsingNamespaces.Values) & whatever is currently loaded into the AppDomain.This ensures the newly compiled object will have everything it needs.
                    Dictionary <string, string> ReferenceAssembliesDic = new Dictionary <string, string>();
                    foreach (string AppDomainAssemFileName in
                             AppDomain.CurrentDomain.GetAssemblies().Where(m => !m.IsDynamic).Select(m => m.Location))
                    {
                        if (File.Exists(AppDomainAssemFileName))
                        {
                            foreach (
                                string DirectoryName in
                                new[]
                            {
                                new FileInfo(AppDomainAssemFileName).DirectoryName,
                                @".",
                                @".\bin",
                                @".\bin\debug",
                                @".\bin\release"
                            })
                            {
                                if (Directory.Exists(DirectoryName))
                                {
                                    foreach (FileInfo _FileInfo in USING_NAMESPACES
                                             .Values
                                             .Select(FileName => String.Format(@"{0}\\{1}", DirectoryName, FileName))
                                             .Where(FilePath => File.Exists(FilePath))
                                             .Select(FilePath => new FileInfo(FilePath))
                                             .Where(_FileInfo => !ReferenceAssembliesDic.ContainsKey(_FileInfo.Name.ToLower())))
                                    {
                                        ReferenceAssembliesDic[_FileInfo.Name.ToLower()] = _FileInfo.FullName;
                                    }
                                }
                            }
                        }
                    }

                    _CompilerParameters.ReferencedAssemblies.AddRange(ReferenceAssembliesDic.Values.ToArray());

                    CompilerResults _CompilerResults = CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                    if (_CompilerResults.Errors.Count == 0)
                    {
                        CompileCSharpCodeDefaultOutDirectory = Path.GetDirectoryName(_CompilerResults.PathToAssembly);
                        CompileCSharpCodeAssemblies[key]     = _CompilerResults.CompiledAssembly;
                    }
                    else
                    {
                        new DirectoryInfo(RequestPaths.GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES)).mkdir().Attributes = FileAttributes.Hidden;

                        if (DebuggingTempFileDirectoryNameParts != null && DebuggingTempFileDirectoryNameParts.Length > 0)
                        {
                            int           i = 0;
                            DirectoryInfo _DirectoryInfo = null;


                            // often there are processes that just won't let there handles go off previous files generated
                            // now we try delete those directories or create a new one with an auto-incremented number when the previous can't be removed
                            do
                            {
                                _DirectoryInfo = new DirectoryInfo(
                                    RequestPaths
                                    .GetPhysicalApplicationPath(
                                        new[] { FOLDER_FOR_COMPILE_TEMPORARY_FILES, StringTransform.SafeIdentifier(string.Join(" ", DebuggingTempFileDirectoryNameParts.Union(new[] { string.Format("{0}", i++) }))) }
                                        .ToArray()));

                                try { _DirectoryInfo.rmdir(); } catch (Exception) { }
                            } while (_DirectoryInfo.Exists);

                            _DirectoryInfo.mkdir();

                            _CompilerParameters.GenerateInMemory        = false;
                            _CompilerParameters.IncludeDebugInformation = true;
                            _CompilerParameters.TempFiles             = new TempFileCollection(_DirectoryInfo.FullName, true);
                            _CompilerParameters.TreatWarningsAsErrors = true;

                            CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                            throw new Exception(string.Format("\"{0}\" Contains runtime the intermediate files of a runtime build (compile) that failed.", _DirectoryInfo.FullName));
                        }
                    }
                }
            }
            return(CompileCSharpCodeAssemblies[key]);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Scans AppDomain for classes implementing the IDocModel & performs all transformations needed to represent them as
        ///     BaseDoc to be served.
        /// </summary>
        /// <param name="DocTypeName">
        ///     Processes only the given DocTypeName the IDocModel represents. If a IDocModel can not be
        ///     located through out the AppDomain nothing will be processed & no IDocRev will be imported. If no DocTypeName is
        ///     specified all IDocModel located will be processed.
        /// </param>
        public static List <ImporterLightDoc> ReadIDocModelCSharpCode()
        {
            List <ImporterLightDoc> List_ImporterLightDoc = new List <ImporterLightDoc>();

            //TODO:Validate POCO utilizes correct title-case underscore separated labeling practices
            //TODO:add a placeholder file describing what goes in the given DocTypeName's form root directory
            var IDocModelItems = AppDomain
                                 .CurrentDomain
                                 .GetAssemblies()
                                 .SelectMany(a => a.GetTypes())
                                 .Distinct()
                                 .Where(typ => (typ.GetInterfaces().Any(i => i == typeof(IDocModel))))
                                 .Select(type => new
            {
                type,
                DirectoryInfo = new DirectoryInfo(FilesystemTemplateController.GetDocDirectoryPath(type.Name)).mkdir(),
                myschemaXsd   = XsdExporter.ExportSchemas(
                    type.Assembly,
                    new List <string> {
                    type.Name
                },
                    RuntimeTypeNamer.CalcSchemaUri(type.Name)).First()
            });

            foreach (var docTypeDirectoryInfo in IDocModelItems)
            {
                string filepath = string.Format(@"{0}{1}", docTypeDirectoryInfo.DirectoryInfo.FullName, Runtime.MYSCHEMA_XSD_FILE_NAME);

                // always (over)write the xsd as this will always be generated by and for Rudine.Core regardless of the IDocInterpreter that is handling
                // compare the existing xsd on disk with the one generated here (excluding the "rolling" namespace) to see if anything has changed
                if (
                    !File.Exists(filepath)
                    ||
                    RuntimeTypeNamer.VALID_CSHARP_NAMESPACE_PART_MATCH.Replace(docTypeDirectoryInfo.myschemaXsd, string.Empty) != RuntimeTypeNamer.VALID_CSHARP_NAMESPACE_PART_MATCH.Replace(File.ReadAllText(filepath), string.Empty)
                    )
                {
                    File.WriteAllText(string.Format(@"{0}{1}", docTypeDirectoryInfo.DirectoryInfo.FullName, Runtime.MYSCHEMA_XSD_FILE_NAME), docTypeDirectoryInfo.myschemaXsd);
                }

                // create placeholder App_Code\DocTypeName.c_ files for developer to get started with myschema.xsd generation via cSharp file editing & thus auto translating
                string App_Code_Directory_Fullname = RequestPaths.GetPhysicalApplicationPath(Resources.App_Code_DirectoryPath);
                if (Directory.Exists(App_Code_Directory_Fullname))
                {
                    Tasker.StartNewTask(() =>
                    {
                        foreach (string DocTypeName in DocExchange.DocTypeDirectories())
                        {
                            if (!IDocModelItems.Any(m => m.DirectoryInfo.Name.Equals(DocTypeName, StringComparison.CurrentCultureIgnoreCase)))
                            {
                                string cSharpCodeFileName = string.Format(@"{0}\{1}.c_", App_Code_Directory_Fullname, DocTypeName);
                                string xsdFileName        = RequestPaths.GetPhysicalApplicationPath("doc", DocTypeName, Runtime.MYSCHEMA_XSD_FILE_NAME);
                                string xsd          = File.ReadAllText(xsdFileName);
                                string myclasses_cs = new Xsd().ImportSchemasAsClasses(
                                    new[] { xsd },
                                    null,
                                    CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateProperties,
                                    new StringCollection());

                                if (!File.Exists(cSharpCodeFileName) || File.ReadAllText(cSharpCodeFileName) != myclasses_cs)
                                {
                                    File.WriteAllText(cSharpCodeFileName, myclasses_cs);
                                    File.SetAttributes(cSharpCodeFileName, FileAttributes.Hidden);
                                }
                            }
                        }
                        return(true);
                    });
                }
            }
            return(List_ImporterLightDoc);
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Expects the directory to contain an infopath manifest.xsf & template.xml files. The contents are then persisted &
        ///     indexed by DocTypeName & DocTypeRev (aka solutionVersion) for OpenStream & OpenText operations. As of this writing,
        ///     this application must have write access to the parent folder of the given directory for cab compression operations.
        /// </summary>
        /// <param name="importFolderPath"></param>
        /// <param name="workingFolderPath">default is parent of importFolderPath</param>
        public static List <ImporterLightDoc> ImportContentFolder(string sourceFolderPath, string workingFolderPath = null)
        {
            List <ImporterLightDoc> List_ImporterLightDoc = new List <ImporterLightDoc>();

            DirectoryInfo _DirectoryInfo = new DirectoryInfo(sourceFolderPath);

            if (workingFolderPath == null)
            {
                workingFolderPath = RequestPaths.GetPhysicalApplicationPath("import");
            }

            //// ensure the import folder actually exists
            //Task.Factory.StartNew(() =>{
            new DirectoryInfo(workingFolderPath)
            .mkdir()
            .Attributes = FileAttributes.NotContentIndexed | FileAttributes.Hidden;
            //});

            string DocMD5, DocTypeVer;
            string DocTypeName = ScanContentFolder(_DirectoryInfo, out DocTypeVer, out DocMD5);

            if (!ServiceController.LuceneController.List(new List <string> {
                "DOCREV"
            }, null, null, DocMD5).Any())
            {
                try
                {
                    IList <string> relativeFilePathsInDirectoryTree = GetRelativeFilePathsInDirectoryTree(_DirectoryInfo.FullName, true);
                    IDictionary <string, string> files = CreateStringDictionary(relativeFilePathsInDirectoryTree, relativeFilePathsInDirectoryTree);
                    //the folder's contents compressed
                    string cabFilePath = string.Format(@"{0}\{1}_{2}.cab", workingFolderPath, DocTypeName, FileSystem.CleanFileName(DocTypeVer));

                    Dictionary <string, string> DocIdKeys = new Dictionary <string, string>
                    {
                        { "TargetDocTypeName", DocTypeName },
                        { "TargetDocTypeVer", DocTypeVer }
                    };

                    //TODO:Unit Test this! Generating in memory cab files has not been tested at all!!!
                    using (CompressionEngine _CompressionEngine = new CabEngine {
                        CompressionLevel = CompressionLevel.Max
                    })
                        using (ArchiveMemoryStreamContext _ArchiveMemoryStreamContext = new ArchiveMemoryStreamContext(cabFilePath, sourceFolderPath, files)
                        {
                            EnableOffsetOpen = true
                        })
                            using (MemoryStream _TargetDocTypeFilesMemoryStream = new MemoryStream())
                            {
                                _CompressionEngine.Pack(_ArchiveMemoryStreamContext, files.Keys);

                                string fileName       = Path.GetFileName(cabFilePath);
                                uint   fileNameLength = (uint)fileName.Length + 1;
                                byte[] fileNameBytes  = Encoding.Unicode.GetBytes(fileName);

                                using (MemoryStream CabFileMemoryStream = _ArchiveMemoryStreamContext.DictionaryStringMemoryStream.Values.First())
                                {
                                    CabFileMemoryStream.Position = 0;
                                    using (BinaryReader _BinaryReader = new BinaryReader(CabFileMemoryStream))
                                        using (BinaryWriter _BinaryWriter = new BinaryWriter(_TargetDocTypeFilesMemoryStream))
                                        {
                                            // Write the InfoPath attachment signature.
                                            _BinaryWriter.Write(new byte[] { 0xC7, 0x49, 0x46, 0x41 });

                                            // Write the default header information.
                                            _BinaryWriter.Write((uint)0x14); // size
                                            _BinaryWriter.Write((uint)0x01); // version
                                            _BinaryWriter.Write((uint)0x00); // reserved

                                            // Write the file size.
                                            _BinaryWriter.Write((uint)_BinaryReader.BaseStream.Length);

                                            // Write the size of the file name.
                                            _BinaryWriter.Write(fileNameLength);

                                            // Write the file name (Unicode encoded).
                                            _BinaryWriter.Write(fileNameBytes);

                                            // Write the file name terminator. This is two nulls in Unicode.
                                            _BinaryWriter.Write(new byte[] { 0, 0 });

                                            // Iterate through the file reading data and writing it to the outbuffer.
                                            byte[] data      = new byte[64 * 1024];
                                            int    bytesRead = 1;

                                            while (bytesRead > 0)
                                            {
                                                bytesRead = _BinaryReader.Read(data, 0, data.Length);
                                                _BinaryWriter.Write(data, 0, bytesRead);
                                            }
                                        }

                                    // these contents will be stored in yet another document as an attached cab file
                                    IDocRev_Gen2 DocRevBaseDoc = (IDocRev_Gen2)DocInterpreter.Instance.Create("DOCREV");

                                    DocRevBaseDoc.DocChecksum        = int.MinValue;
                                    DocRevBaseDoc.DocIdKeys          = DocIdKeys;
                                    DocRevBaseDoc.DocStatus          = true;
                                    DocRevBaseDoc.DocTitle           = String.Format("{0} {1}", DocTypeName, DocTypeVer);
                                    DocRevBaseDoc.DocTypeName        = "DOCREV";
                                    DocRevBaseDoc.TargetDocTypeFiles = _TargetDocTypeFilesMemoryStream.ToArray();
                                    DocRevBaseDoc.TargetDocTypeName  = DocTypeName;
                                    DocRevBaseDoc.TargetDocTypeVer   = DocTypeVer;

                                    /*
                                     * BANDAID: DOCREV
                                     * (search for this though out the code for more on DOCREV snafus in general),
                                     * earlier implementations of DOCREV did not have a TargetDocMD5 property, the IDocRev must be compatible with all versions of this object
                                     */
                                    foreach (PropertyInfo p in DocRevBaseDoc.GetType().GetProperties().Where(p => p.Name == "TargetDocMD5"))
                                    {
                                        p.SetValue(DocRevBaseDoc, DocMD5, null);
                                    }

                                    List_ImporterLightDoc.Add(
                                        new ImporterLightDoc {
                                        LightDoc = ServiceController.Instance.Import(DocRevBaseDoc.GetDocData())
                                    });
                                }
                            }
                }
                catch (ThreadAbortException) { }
            }