Click here to Skip to main content
15,896,493 members
Articles / Web Development / ASP.NET

DNN Module Packager

Rate me:
Please Sign up or sign in to vote.
4.61/5 (11 votes)
22 Nov 2006CPOL2 min read 64.3K   1K   28  
A utility that creates a DotNetNuke manifest file and packages a module.
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Collections.Specialized;
using ICSharpCode.SharpZipLib.Zip;


namespace DNN_Module_Packager
{
    class FileUtilities
    {
        private enum FILE_TYPES { UNKNOWN, DNN, ZIP, ASSEMBLY }

        /// <summary>
        /// Gets an array of filepaths the user has selected in the file-open dialog
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        private static string[] GetOpenFiles(FILE_TYPES fileType)
        {
            string[] sFilePaths = null;

            OpenFileDialog openFile = new OpenFileDialog();            
            openFile.Multiselect = true;
            openFile.Filter = GetFilterForFileType(fileType);            

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                sFilePaths = openFile.FileNames;
            }

            return sFilePaths;
        }
        
        /// <summary>
        /// Gets the filepath the user has selected in the file-open dialog
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        private static string GetOpenFilePath(FILE_TYPES fileType)
        {
            string sFilePath = string.Empty;

            OpenFileDialog openFile = new OpenFileDialog();            
            openFile.Filter = GetFilterForFileType(fileType);            

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                sFilePath = openFile.FileName;
            }

            return sFilePath;
        }

        /// <summary>
        /// Returns the filter string for the file-type
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        private static string GetFilterForFileType(FILE_TYPES fileType)
        {
            string sFilter = "All files (*.*)|*.*";

            switch (fileType)
            {
                case FILE_TYPES.DNN:
                    sFilter = "DNN Config files (*.dnn)|*.dnn|All files (*.*)|*.*";
                    break;//.gensln

                case FILE_TYPES.ZIP:
                    sFilter = "Zip Archive files (*.zip)|*.zip|All files (*.*)|*.*";
                    break;//.genproj

                case FILE_TYPES.ASSEMBLY:
                    sFilter = "Assembly files (*.dll)|*.dll|C# Source files (*.cs)|*.cs|VB.NET Source files (*.vb)|*.vb|All files (*.*)|*.*";
                    break;//.cs;.vb, etc

                default:
                    sFilter = "All files (*.*)|*.*";
                    break;
            }

            return sFilter;
        }

        /// <summary>
        /// Returns the filepath the user selected in the save-file dialog
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        private static string GetSaveFilePath(FILE_TYPES fileType)
        {
            string sFilePath = string.Empty;

            SaveFileDialog saveFile = new SaveFileDialog();            
            saveFile.Filter = GetFilterForFileType(fileType);            

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                sFilePath = saveFile.FileName;
            }

            return sFilePath;
        }

        /// <summary>
        /// Returns the path the user selected in the browse-for-file dialog
        /// </summary>
        /// <param name="sdescr"></param>
        /// <returns></returns>
        public static string GetBrowseForPath(string sdescr)
        {
            string sPath = string.Empty;

            FolderBrowserDialog fbdBrowser = new FolderBrowserDialog();
            fbdBrowser.Description = sdescr;            
            fbdBrowser.ShowNewFolderButton = true;

            if (fbdBrowser.ShowDialog() == DialogResult.OK)
            {
                sPath = fbdBrowser.SelectedPath;
            }

            return sPath;
        }

        /// <summary>
        /// Public accessor so we can hide the filetypes
        /// </summary>
        /// <returns></returns>
        public static string GetOpenDnnFile()
        {
            return GetOpenFilePath(FILE_TYPES.DNN);
        }

        /// <summary>
        /// Public accessor so we can hide the filetypes
        /// </summary>
        /// <returns></returns>
        public static string[] GetOpenAssemblyFiles()
        {
            return GetOpenFiles(FILE_TYPES.ASSEMBLY);
        }

        /// <summary>
        /// Public accessor so we can hide the filetypes
        /// </summary>
        /// <returns></returns>
        public static string GetSaveZipFile()
        {
            return GetSaveFilePath(FILE_TYPES.ZIP);
        }

        /// <summary>
        /// Reads and returns the contents of a file into a string
        /// </summary>
        /// <param name="sFilePath"></param>
        /// <returns></returns>
        public static string ReadFileContents(string sFilePath)
        {
            FileStream file = null;
            StreamReader sr = null;
            string sContents = string.Empty;

            try
            {               
                // make sure we're allowed to overwrite the file if it exists
                if (File.Exists(sFilePath) == false)
                {
                    throw new Exception("Cannot read the file '" + sFilePath + "' because it does not exist!");
                }

                // Specify file, instructions, and priveledges
                file = new FileStream(sFilePath, FileMode.OpenOrCreate, FileAccess.Read);

                // Create a new stream to read from a file
                sr = new StreamReader(file);

                // Read contents of file into a string
                sContents = sr.ReadToEnd();                
            }
            catch (Exception ex)
            {
                throw new Exception("ReadFileContents() failed with error: " + ex.Message);
            }
            finally
            {
                // Close StreamReader
                if (sr != null)
                    sr.Close();

                // Close file
                if (file != null)
                    file.Close();
            }

            return sContents;
        }

        /// <summary>
        /// Writes a string/contents to a given filepath
        /// </summary>
        /// <param name="sFilePath"></param>
        /// <param name="sContents"></param>
        /// <param name="bOverwrite"></param>
        public static void WriteFileContents(string sFilePath, string sContents, bool bOverwrite)
        {
            FileStream file = null;
            StreamWriter sw = null;

            try
            {
                // make sure we're allowed to overwrite the file if it exists
                if (bOverwrite == false)
                {
                    if (File.Exists(sFilePath) == true)
                    {
                        throw new Exception("Cannot write the file '" + sFilePath + "' because it already exists!");
                    }
                }

                // Specify file, instructions, and privelegdes
                file = new FileStream(sFilePath, FileMode.OpenOrCreate, FileAccess.Write);

                // Create a new stream to write to the file
                sw = new StreamWriter(file);

                // Write a string to the file
                sw.Write(sContents);
            }
            catch (Exception ex)
            {
                throw new Exception("WriteFileContents() failed with error: " + ex.Message);
            }
            finally
            {
                // Close StreamWriter
                if (sw != null)
                    sw.Close();

                // Close file
                if (file != null)
                    file.Close();
            }
        }


        /// <summary>
        /// Creates a relative path from one file or folder to another.
        /// </summary>
        /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param>
        /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
        /// <returns>The relative path from the start directory to the end path.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static string RelativePathTo(string fromDirectory, string toPath)
        {
            if ((fromDirectory == null) || (fromDirectory.Trim() == string.Empty))
            {
                return string.Empty;
            }

            if ((toPath == null) || (toPath.Trim() == string.Empty))
            {
                return string.Empty;
            }

            if (System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath))
            {
                if (string.Compare(System.IO.Path.GetPathRoot(fromDirectory),
                System.IO.Path.GetPathRoot(toPath), true) != 0)
                {
                    return toPath;
                    //throw new ArgumentException(string.Format("The paths '{0} and '{1}' have different path roots.", fromDirectory, toPath));
                }
            }

            StringCollection relativePath = new StringCollection();
            string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar);
            string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar);
            int length = Math.Min(fromDirectories.Length, toDirectories.Length);
            int lastCommonRoot = -1;
            // find common root
            for (int x = 0; x < length; x++)
            {
                if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
                    break;
                lastCommonRoot = x;
            }
            if (lastCommonRoot == -1)
            {
                throw new ArgumentException(
                string.Format("The paths '{0} and '{1}' do not have a common prefix path.",
                fromDirectory, toPath));
            }
            // add relative folders in from path
            for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
                if (fromDirectories[x].Length > 0)
                    relativePath.Add("..");
            // add to folders to path
            for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
                relativePath.Add(toDirectories[x]);
            // create relative path
            string[] relativeParts = new string[relativePath.Count];
            relativePath.CopyTo(relativeParts, 0);
            string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts);
            return newPath;
        }

        /// <summary>
        /// Returns an array of all the filepaths of the files in a folder/path (with recursion)
        /// </summary>
        /// <param name="path"></param>
        /// <param name="recursive"></param>
        /// <returns></returns>
        public static ArrayList GetFilesInFolder(string path, bool recursive)
        {
            ArrayList listFiles = new ArrayList();
            DoFileSearch(path, listFiles, recursive);

            return listFiles;
        }

        /// <summary>
        /// Helper/worker function for the GetFilesInFolder() function
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="listFiles"></param>
        /// <param name="recursive"></param>
        private static void DoFileSearch(string folderPath, ArrayList listFiles, bool recursive)
        {
            if (recursive)
            {
                foreach (string folder in Directory.GetDirectories(folderPath))
                {
                    DoFileSearch(folder, listFiles, recursive);
                }
            }

            listFiles.AddRange(Directory.GetFiles(folderPath));
        }

        /// <summary>
        /// Copies a raw byte-stream from one source to another
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        private static void CopyStream(Stream source, Stream destination)
        {
            byte[] buffer = new byte[4096];
            int countBytesRead;
            while ((countBytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
            {
                destination.Write(buffer, 0, countBytesRead);
            }
        }

        /// <summary>
        /// Zips an list of files (filepaths) to the specified zip file archive
        /// </summary>
        /// <param name="destinationFileName"></param>
        /// <param name="password"></param>
        /// <param name="aryFiles"></param>
        public static void ZipFiles(string destinationFileName, string password, ArrayList aryFiles)
        {
            FileStream outputFileStream = new FileStream(destinationFileName, FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(outputFileStream);
            ZipEntry zipEntry = null;
            FileStream inputStream = null;

            bool isCrypted = false;

            //encrypt the zip file, if password is given
            if ((password != null) && (password.Length > 0))
            { 
                zipStream.Password = password;
                isCrypted = true;
            }

            foreach (string sfile in aryFiles)
            {
                //save the readonly status and set writable(can't zip readonly files programatically)
                bool breadonly = GetFileLocked(sfile);
                if (breadonly == true)
                {
                    SetFileLocked(sfile, false);
                }

                inputStream = new FileStream(sfile, FileMode.Open);
                zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(sfile));
                
                zipEntry.IsCrypted = isCrypted;
                zipEntry.CompressionMethod = CompressionMethod.Deflated;
                zipStream.PutNextEntry(zipEntry);
                CopyStream(inputStream, zipStream);
                inputStream.Close();
                zipStream.CloseEntry();

                // change the read-only status back to read-only
                if (breadonly == true)
                {
                    SetFileLocked(sfile, true);
                }
            }

            zipStream.Finish();
            zipStream.Close();
        }

        public static bool GetFileLocked(string sFilePath)
        {
            bool bReadOnly = false;

            try
            {
                // if no filename, return
                if (sFilePath.Trim() == string.Empty)
                {
                    return bReadOnly;
                }

                FileInfo fiInfo = new FileInfo(sFilePath);
                if (fiInfo.Exists == true)
                {
                    bReadOnly = fiInfo.IsReadOnly;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("GetFileLocked() failed with error: " + ex.Message);
            }

            return bReadOnly;
        }

        public static void SetFileLocked(string sFilePath, bool bLocked)
        {
            try
            {
                // if no filename, return
                if (sFilePath.Trim() == string.Empty)
                {
                    return;
                }

                FileInfo fiInfo = new FileInfo(sFilePath);
                if (fiInfo.Exists == true)
                {
                    fiInfo.IsReadOnly = bLocked;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("SetFileLocked() failed with error: " + ex.Message);
            }
        }
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
SOFTWARE: Chris Hambleton is a Software Developer with proven experience in developing both web and Windows client-server applications with WPF, ASP.NET, C#, SQL Server, VB.NET, Visual C++, and VB6.

Chris's website is at ChrisHambleton.com and he has a small web-hosting/consulting business called CustomersInFocus.com. He has several other websites such as EzekielWatch.com, iWriterPro.com, and BookBlitzer.com.

WRITING: He has also written several fiction books ("The Time of Jacob's Trouble" and "Endeavor in Time"), available at CWHambleton.com and of course, at Amazon.com (Full Amazon Profile).

Comments and Discussions