Thursday, October 13, 2011

How take back-up an database assembly before adding new changes in MS CRM 4.0

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace CrmPluginAssemblyExtractor
{
    class Program
    {
        static string PluginName = "CloseOpportunities";
        static void Main()
        { 
            SqlParameter param = new SqlParameter("@PluginName", PluginName);

            string connectionString = "Data Source=LOCALHOST;Initial Catalog=ORGANIZATION_MSCRM;Integrated Security=SSPI";

            if (connectionString == null)
            {
                Console.WriteLine("No connection string found.");
                return;
            }


            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("SELECT * FROM PluginAssemblyBase WHERE name = @PluginName", conn);
            cmd.Parameters.Add(param);
            conn.Open();

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet dataset = new DataSet();
            adapter.Fill(dataset);

            if (dataset.Tables.Count == 0 || dataset.Tables[0].Rows.Count == 0)
            {
                Console.WriteLine("No plugin assembly found.");
                return;
            }

            foreach (DataRow row in dataset.Tables[0].Rows)
            {

                string content = (string)row["content"];
                byte[] filebytes = Convert.FromBase64String(content);
                FileStream fs = new FileStream((string)row["name"] + ".dll", FileMode.CreateNew, FileAccess.Write, FileShare.None);
                fs.Write(filebytes, 0, filebytes.Length);
                fs.Close();
            }
        }
    }
}