1

I am using following code to create SQL Server CE database file programmatically. I am using C# 2008.

    /* Create a new SQL Server CE database file programatically */
    protected void CreateDB(string _databaseFileName, bool _encryptFile, string _password)
    {
        if (File.Exists(_databaseFileName))
            MessageBox.Show("A file with this name already exists.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        else
        {
            string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", _databaseFileName, _password);
            SqlCeEngine engine = new SqlCeEngine(connectionString);
            engine.CreateDatabase();
        }
    }

I want to improve the above code. My queries are below:

  1. This method is contained in a protected class. I want these methods to be called directly without creating an instance of this class. Suggest a way with no overhead.

  2. Though I am passing a bool to determine whether the user wants to encrypt file or not, but not used in the connection string line. I am not following which other parameter need to be included for encryption and how to include encryption algorithm.

  3. I want to include exception handling with least overhead. I want to include "using", but not following how to modify the above code with this.

1
  • 1
    Sounds like an interview/exam question almost. Commented Nov 10, 2010 at 19:41

1 Answer 1

3
  1. Make the method static.
  2. If you include a password in the connection string, the database file is automatically encrypted.
  3. Not sure what you mean by this one. You should be catching SqlCeException in the else. Also, you should wrap the SqlCeEngine in a using statement.

    try
    {
       string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", _databaseFileName, _password);
       using (SqlCeEngine engine = new SqlCeEngine(connectionString))
       {
          engine.CreateDatabase();
       }
    }
    catch (SqlCeException)
    {
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to use try..Catch. Secondly, I want to include the encryption algorithm.
Not sure how you are going to handle exceptions without a try..catch. Why don't you want to use a try block? I'm not sure if you can set the encryption algorithm or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.