Click here to Skip to main content
15,891,513 members
Articles / Desktop Programming / WPF

Using the Microsoft Desktop Stack – Part 3: Using Entity Framework 4 in an MVVM Application

Rate me:
Please Sign up or sign in to vote.
4.73/5 (21 votes)
17 Apr 2011CPOL25 min read 73.6K   4.9K   56  
This article, shows how to integrate Entity Framework 4 into a WPF application using the MVVM pattern.
using System;
using System.IO;
using System.Reflection;
using log4net;

namespace MsDesktopStackDemo.Services
{
    /// <summary>
    /// Provides file services to the application.
    /// </summary>
    public class FileServices
    {
        #region Fields

        // Member variables
        private static readonly ILog m_Logger = LogManager.GetLogger("FileServices");

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets a file path to the data file for this app.
        /// </summary>
        /// <returns>A file path to the data file for this app.</returns>
        public static string GetDataFilePath()
        {
            // Log invocation
            m_Logger.Info("FileServices.GetDataFilePath() invoked.");

            /* If the app was installed on this machine using the Installer project 
             * included in the demo, then the data file (Books.sdf) was copied to the 
             * Windows CommonDocuments folder on install. If the app is running from 
             * source code in Visual Studio, then the app was copied to the application 
             * output folder on compile. So, we check both locations for the data file. */

            // Initialize
            string dataFilePath;

            // Search Windows CommonDocuments folder for data file
            var foundFile = SearchCommonDocumentsFolder(@"MsDesktopStackDemo\Books.sdf", out dataFilePath);

            // Search application output folder for data file
            if (! foundFile)
            {
                foundFile = SearchApplicationOutputFolder("Books.sdf", out dataFilePath);
            }

            // If file not found in either location, throw exception
            if (!foundFile)
            {
                var errMsg = "Data file 'Books.sdf' was not found.";
                m_Logger.Error(errMsg);
                throw new ApplicationException(errMsg);
            }

            // Log completion
            m_Logger.Info("FileServices.GetDataFilePath() completed.");

            //Set return value
            return dataFilePath;
        }

        /// <summary>
        /// Gets a file path to the folder containing the cover art used by this app.
        /// </summary>
        /// <returns>A file path to the folder containing the cover art used by this app.</returns>
        public static string GetCoversFolderPath()
        {
            // Log invocation
            m_Logger.Info("FileServices.GetCoversFolderPath() invoked.");

            /* We have to search both the Windows CommonDocuments folder and the
             * application output folderfor the cover art folder. See comments to 
             * GetDataFilePath(). */

            // Initialize
            string coverFilePath;

            /* We will search for the folder by searching for a file that should be in 
             * the folder. If we find the file, we have found the folder. I wouldn't
             * do this in a production app--I would test for the folder explicitly. But
             * doing things this way simplifies things for the demo. */

            // Search Windows CommonDocuments folder for data file
            var foundFile = SearchCommonDocumentsFolder(@"MsDesktopStackDemo\Covers\Flatlander.png", out coverFilePath);

            // Search application output folder for data file
            if (!foundFile)
            {
                foundFile = SearchApplicationOutputFolder(@"Covers\Flatlander.png", out coverFilePath);
            }

            // If file not found in either location, throw exception
            if (!foundFile)
            {
                var errMsg = "Cover art folder was not found.";
                m_Logger.Error(errMsg);
                throw new ApplicationException(errMsg);
            }

            // Get folder path from found file
            var coversFolderPath = Path.GetDirectoryName(coverFilePath);
            m_Logger.Info(String.Format("Cover art folder path: {0}", coversFolderPath));

            // Log completion
            m_Logger.Info("FileServices.GetDataFilePath() completed.");

            // Set return value
            return coversFolderPath;
        }
        
        #endregion

        #region Private Methods

        /// <summary>
        /// Searches the Windows CommonDocuments folder for a named file.
        /// </summary>
        /// <param name="fileSpec">The file to search for. Can be either a name or a partial path.</param>
        /// <param name="path">The path tested by the method.</param>
        /// <returns>True if the file was found; false otherwise.</returns>
        private static bool SearchCommonDocumentsFolder(string fileSpec, out string path)
        {
            // Log invocation
            m_Logger.Info("FileServices.SearchCommonDocumentsFolder() invoked.");

            // Look for file in Windows CommonDocuments folder
            var commonDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
            path = Path.Combine(commonDocsPath, fileSpec);
            var foundFile = File.Exists(path);

            // Log result
            string s = foundFile ? String.Empty : " not";
            string resultMsg  = String.Format("File '{0}'{1} found in Windows CommonDocuments folder.", fileSpec, s);
            m_Logger.Info(resultMsg);

            // Log completion
            m_Logger.Info("FileServices.SearchCommonDocumentsFolder() completed.");

            // Set return value
            return foundFile;
        }

        /// <summary>
        /// Searches the application output folder for a named file.
        /// </summary>
        /// <param name="fileSpec">The file to search for. Can be either a name or a partial path.</param>
        /// <param name="path">The path tested by the method.</param>
        /// <returns>True if the file was found; false otherwise.</returns>
        private static bool SearchApplicationOutputFolder(string fileSpec, out string path)
        {
            // Log invocation
            m_Logger.Info("FileServices.SearchApplicationOutputFolder() invoked.");

            // Get application output folder
            var appOutputFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            if(appOutputFolder == null)
            {
                var errMsg = "Application output path returned null.";
                m_Logger.Error(errMsg);
                throw new ApplicationException(errMsg);
            }
            // Look for file in application output folder
            path = Path.Combine(appOutputFolder, fileSpec);
            var foundFile = File.Exists(path);

            // Log result
            string s = foundFile ? String.Empty : " not";
            string resultMsg = String.Format("File '{0}'{1} found in application output folder.", fileSpec, s);
            m_Logger.Info(resultMsg);

            // Log completion
            m_Logger.Info("FileServices.SearchApplicationOutputFolder() completed.");

            // Set return value
            return foundFile;
        }

        #endregion

    }
}

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 (Senior) Foresight Systems
United States United States
David Veeneman is a financial planner and software developer. He is the author of "The Fortune in Your Future" (McGraw-Hill 1998). His company, Foresight Systems, develops planning and financial software.

Comments and Discussions