// Other properties and fields

    public Logger(DatabaseManagement dbManagement)
    {
        this.dbManagement = dbManagement;
        // other constructor stuff
    }
예제 #2
0
        private void FormMain_Load(object sender, EventArgs e)
        {
            try
            {
                List <string> rgSqlInst = DatabaseInstanceQuery.GetInstances();

                m_bwProcess.RunWorkerAsync();

                if (!File.Exists("index.chm"))
                {
                    localHelpToolStripMenuItem.Enabled = false;
                }

                if (rgSqlInst == null || rgSqlInst.Count == 0)
                {
                    setStatus("You must download and install 'Microsoft SQL' or 'Microsoft SQL Express' first!");
                    setStatus("see 'https://www.microsoft.com/en-us/sql-server/sql-server-editions-express'");
                    setStatus("");
                    return;
                }
                else if (rgSqlInst.Count == 1)
                {
                    if (rgSqlInst[0] != ".\\MSSQLSERVER")
                    {
                        EntitiesConnection.GlobalDatabaseServerName = rgSqlInst[0];
                    }
                }
                else
                {
                    FormSqlInstances dlg = new FormSqlInstances(rgSqlInst);

                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        if (dlg.Instance != ".\\MSSQLSERVER")
                        {
                            EntitiesConnection.GlobalDatabaseServerName = dlg.Instance;
                        }
                    }
                    else
                    {
                        setStatus("You are NOT connected to SQL.");
                    }
                }

                setStatus("Using SQL Instance '" + EntitiesConnection.GlobalDatabaseServerName + "'", false);

                DatabaseManagement dbMgr = new DatabaseManagement("DNN", "", EntitiesConnection.GlobalDatabaseServerName);
                bool      bExists;
                Exception err = dbMgr.DatabaseExists(out bExists);

                if (err != null)
                {
                    setStatus("ERROR: " + err.Message);
                }
                else if (!bExists)
                {
                    createDatabaseToolStripMenuItem_Click(this, new EventArgs());
                }
                else
                {
                    setStatus("Using database '" + dbMgr.Name + "'");
                }

                setStatus("");

                m_autoTest.OnProgress  += m_autoTest_OnProgress;
                m_autoTest.OnCompleted += m_autoTest_OnCompleted;

                setStatus("The MyCaffe Test App supports two different types of automated testing:");
                setStatus(" 1.) User interface based automated testing via the 'Test | Run Autotests UI', and");
                setStatus(" 2.) Server based automated testing via the 'Test | Start Server Autotests' menu.");
                setStatus("Server auto tests can easily integrate into other applications.");
                setStatus("NOTE: Known test failures are pre-set with a FAILURE status.");
                setStatus("----------------------------------------------------------------------------------");

                DatasetFactory factory  = new DatasetFactory();
                int            nCifarID = factory.GetDatasetID("CIFAR-10");
                int            nMnistID = factory.GetDatasetID("MNIST");

                if (nCifarID == 0 || nMnistID == 0)
                {
                    setStatus(" !Before running any automated tests, make sure to load the following datasets:");

                    if (nCifarID == 0)
                    {
                        setStatus("    CIFAR-10");
                    }

                    if (nMnistID == 0)
                    {
                        setStatus("    MNIST (1 channel)");
                    }

                    setStatus(" see the 'Database' menu.");
                }

                m_dlgWait = new FormWait();
                m_bwInit.RunWorkerAsync();
                m_dlgWait.ShowDialog();
                m_bwUrlCheck.RunWorkerAsync();
            }
            catch (Exception excpt)
            {
                string strErr = excpt.Message;

                if (excpt.InnerException != null)
                {
                    strErr += " " + excpt.InnerException.Message;
                }

                if (strErr.Contains("login") && strErr.Contains("DNN"))
                {
                    strErr += " Make sure that this user can access the DNN database - this setting is made using the SQL Management Studio.";
                }

                setStatus("ERROR: " + strErr);
            }
        }
예제 #3
0
 public ChangePasswordPage()
 {
     DBMgr = new DatabaseManagement();
     InitializeComponent();
 }
예제 #4
0
        /// <summary>
        /// Post method for receiving User/Password. Server receive an HTTP message containing an 'User' object containing the User's code and pin used for authentication.
        /// Metodo Post per la ricezione di una coppia User/Password. Il server riceve un HTTP message che contiene un oggetto 'User' che contiene la matricola e il pin dell'Utente usati per l'autenticazione.
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public HttpResponseMessage Post(Utente u)
        {
            User   ricerca = null;
            string msg     = "OK";
            bool   login   = true;
            HttpResponseMessage response = null;

            System.Net.HttpStatusCode httpStatusCode = System.Net.HttpStatusCode.Created;

            //inizializzazione db e ricerca utente in base alla matricola(codice)
            DatabaseManagement db = new DatabaseManagement(strConn, LogPath);

            try
            {
                int codice = Convert.ToInt32(u.User);
                ricerca = db.SelectSimpleUser(codice);

                if (ricerca == null)
                {
                    //non ho trovato nessun utente semplice
                    ricerca = db.SelectAdministrator(codice);
                }

                if (ricerca != null)
                {
                    //converto in bytes la stringa da codificare
                    byte[] data = Encoding.ASCII.GetBytes(u.Pwd);
                    string result;

                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    //ottengo lo SHA1 dei dati
                    result = Encoding.ASCII.GetString(sha1.ComputeHash(data));

                    //confronto lo SHA1 della pwd inviata con lo SHA1 di quella nel DB
                    if (result != ricerca.Password)
                    {
                        msg            = "Invalid Password";
                        httpStatusCode = System.Net.HttpStatusCode.Unauthorized;
                        login          = false;
                    }
                }
                else
                {
                    msg            = "Invalid Username";
                    httpStatusCode = System.Net.HttpStatusCode.Forbidden;
                    login          = false;
                }
                //utente e password corrispondono
                if (login)
                {
                    //inserisco un record nella tabella degli ingressi
                    db.InserAccessUser(ricerca.Codice, DateTime.Now, DatabaseManagement.LOGIN, null);

                    //invio ad ogni amministratore una mail
                    List <Administrator> AdminList = db.ShowAdministrators();

                    if (AdminList.Count > 0)
                    {
                        foreach (Administrator a in AdminList)
                        {
                            MailManagement mailmanagment = new MailManagement(a.MailAddress, a.MailPassword);
                            mailmanagment.SendMailToAdmin(a.MailAddress, ricerca, DateTime.Now);
                        }
                    }
                }
            }
            catch (DatabaseException e)//DB exception
            {
                httpStatusCode = System.Net.HttpStatusCode.InternalServerError;
                msg            = e.Mex;
                db.NewErrorLog("ANOMALY-" + e.Message, DateTime.Now);
            }
            catch (Exception e)
            {
                //in caso di errore la response diventa http 500
                httpStatusCode = System.Net.HttpStatusCode.InternalServerError;
                msg            = e.Message;
                db.NewErrorLog("ANOMALY-" + e.Message, DateTime.Now);
            }
            finally
            {
                db.CloseConnection();

                response = Request.CreateResponse(httpStatusCode, msg);

                //aggiungo un messaggio allo status code
                response.ReasonPhrase = msg;
            }

            return(response);
        }
예제 #5
0
    //[ScriptMethod(UseHttpGet = false)]
    public static string delete(Guid userid, string websitename, string username)
    {
        string msg;

        // Response.Write(userid);
        // Response.Write(websitename);
        msg = "Hello";
        //  datalayer dl = new datalayer();
        MyProjectDataContext da = new MyProjectDataContext();
        var q = from a in da.Websites
                where a.UserId == userid && a.WebsiteName == websitename
                select a;
        int websiteid = GetWebsiteId(userid, username, websitename);
        var q1        = from b in da.WebsitePages
                        where b.WebsiteId == websiteid
                        select b;

        foreach (var o in q1)
        {
            da.WebsitePages.DeleteOnSubmit(o);   // removing foreign key references
        }
        foreach (var o in q)
        {
            da.Websites.DeleteOnSubmit(o);
        }

        try
        {
            //deleting name from drop down
            web_design_CreateWebsite ob = new web_design_CreateWebsite();
            ob.bind_website_ddl();
            //ob.ddl_select_website.Items.Remove(websitename);
            //--------------------------

            //deleting website folder and files

            string             subPath = "~/web-design/" + username + "/" + websitename + "/";
            System.Web.UI.Page p       = new System.Web.UI.Page(); //creating instance of object

            bool exists = System.IO.Directory.Exists(p.Server.MapPath(subPath));

            if (exists)
            {
                System.IO.Directory.Delete(p.Server.MapPath(subPath), true);
            }
            //deleting db
            DatabaseManagement dbManage = new DatabaseManagement();
            dbManage.DeleteDatabaseByWebsiteName(userid, websitename, username);
            //  end-------------
            da.SubmitChanges();

            msg = "success";
        }
        catch
        {
            msg = "error";
        }

        //   msg=dl.Delete_Website(userid, websitename);
        return(msg);
    }
        /// <summary>
        /// Given an assembly containing one ore more DictionarySteps, applies specified dictionary steps into database model and physical database.
        /// </summary>
        /// <param name="assembly">Assembly containing dictionary steps</param>
        /// <param name="connectionString">Connection string to SuperOffice database where steps are to be applied.</param>
        /// <param name="tablePrefix">SuperOffice table prefix</param>
        /// <param name="dbMajor">Major version of SuperOffice database.</param>
        /// <param name="dbMinor">Minor version of SuperOffice database.</param>
        /// <param name="stepsToInclude">Name of the DictionaryStep to apply. Useful when an assembly contains more then one.</param>
        /// <param name="uninstall">Indicates whether this call should only apply DictionarySteps with a StepNumber equals to int.MaxValue</param>
        /// <param name="progress">Optional progress implementation for reporting progress.</param>
        /// <returns>Array of StepInfo indicating which dictionary steps were applied.</returns>
        internal StepInfo[] ApplySteps(
            string assembly,
            string connectionString,
            string tablePrefix,
            string dbMajor,
            string dbMinor,
            StepInfo[] stepsToInclude,
            bool uninstall,
            IProgressNotification progress)
        {
            DictionaryStepInfo[] result = null;

            try
            {
                // load the assembly into this AppDomain

                var stepAssembly = LoadAssembly(assembly);

                var fileLogger = new SuperOffice.CD.DSL.Logging.FileLogger(Environment.CurrentDirectory + "\\appliedstep.log");

                using (var connection = DbConnectionProvider.GetConnection(connectionString, dbMajor, dbMinor))
                {
                    using (var dbm = DatabaseManagement.CreateInstance(tablePrefix, connection, fileLogger, progress))
                    {
                        var model   = dbm.ReadDatabaseModel();
                        var dbState = dbm.InspectDatabase();

                        // ensure we are talking to a SuperOffice database version >= 8.1

                        if (dbState == DatabaseManagement.DatabaseContent.SuperOfficeCdd)
                        {
                            // get all DictionarySteps in this AppDomain - filter out any .net & SuperOffice assemblies

                            var steps = GetDictionarySteps(stepsToInclude, uninstall);


                            //make sure we only apply steps that were passed in stepsToInclude argument

                            var desiredSteps = new List <DictionaryStep>();

                            foreach (var item in stepsToInclude.OrderBy(st => st.Name).ThenBy(st => st.StepNumber))
                            {
                                var dicStep = steps.Find(s => s.GetAttribute().DictionaryName.Equals(item.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                         s.GetAttribute().StepNumber == item.StepNumber);

                                if (dicStep != null)
                                {
                                    desiredSteps.Add(dicStep);
                                }
                            }

                            // apply DictionarySteps in the Database
                            if (desiredSteps.Count > 0)
                            {
                                result = dbm.ApplyDictionarySteps(new LinkedList <DictionaryStep>(desiredSteps), model);
                            }
                        }

                        if (result == null)
                        {
                            return(null);
                        }

                        return(result.Select(s => new StepInfo {
                            Name = s.Name, StepNumber = s.StepNumber, State = s.State.ToString()
                        }).ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //  Response.Redirect("~/LoanProfile.aspx?id=" + GlobalStringID + "&type=" + GlobalStringType);
        Label1.Text = dummy;
        Label2.Text = dummy;
        Label3.Text = dummy;
        Label4.Text = dummy;
        Label5.Text = dummy;
        Label6.Text = dummy;

        bool flag = true;

        try
        {
            double d = double.Parse(TextBox1.Text);
        }
        catch (Exception ie)
        {
            flag             = false;
            Label1.Text      = "Invalid number";
            Label1.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox1.Text.Equals(dummy))
        {
            flag             = false;
            Label1.Text      = "*";
            Label1.BackColor = System.Drawing.Color.Red;
        }
        try
        {
            double d = double.Parse(TextBox2.Text);
        }
        catch (Exception ie)
        {
            flag             = false;
            Label2.Text      = "Invalid number";
            Label2.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox2.Text.Equals(dummy))
        {
            flag             = false;
            Label2.Text      = "*";
            Label2.BackColor = System.Drawing.Color.Red;
        }
        try
        {
            double d = double.Parse(TextBox3.Text);
        }
        catch (Exception ie)
        {
            flag             = false;
            Label3.Text      = "Invalid number";
            Label3.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox3.Text.Equals(dummy))
        {
            flag             = false;
            Label3.Text      = "*";
            Label3.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox4.Text.Equals(dummy))
        {
            flag             = false;
            Label4.Text      = "*";
            Label4.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox5.Text.Equals(dummy))
        {
            flag             = false;
            Label5.Text      = "*";
            Label5.BackColor = System.Drawing.Color.Red;
        }
        if (TextBox6.Text.Equals(dummy))
        {
            flag             = false;
            Label6.Text      = "*";
            Label6.BackColor = System.Drawing.Color.Red;
        }
        if (flag)
        {
            string amount, sanctiondate, paymentdate, irate, mammount, mor_description, warntee, lealissue;
            amount          = TextBox1.Text;
            sanctiondate    = DropDownList1.SelectedValue + "-" + DropDownList2.SelectedValue + "-" + DropDownList3.SelectedValue;
            paymentdate     = DropDownList4.SelectedValue + "-" + DropDownList5.SelectedValue + "-" + DropDownList6.SelectedValue;
            irate           = TextBox2.Text;
            mammount        = TextBox3.Text;
            mor_description = TextBox4.Text;
            warntee         = TextBox5.Text;
            lealissue       = TextBox6.Text;

            DatabaseManagement dm         = new DatabaseManagement();
            OracleConnection   connection = dm.dbaseConn();
            dm.connOpen(connection);
            string seqquery = "select loan_seq.nextval from dual";
            string lnumber  = dm.ReadRow(seqquery, connection)[0].ToString();
            // string lnumber = "3012";
            double installamount = (double.Parse(amount) * double.Parse(irate)) / 100;
            string query         = "insert into loan values(" + AccountLable.Text + ",'" + lnumber + "'," + amount + ",'" + sanctiondate + "','" + paymentdate + "'," + irate + ",'" + mammount + "','" + mor_description + "','" + warntee + "','" + lealissue + "',to_char(sysdate)," + installamount + ",0)";

            try
            {
                OracleCommand cmd = new OracleCommand(query, connection);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ie)
            {
                //   InsertLabel.Text = query+ ie.Message;
            }
            Session["loannumber"] = lnumber;

            dm.connClose(connection);
            Response.Redirect("~/LoanProfile.aspx");

            /*   dm.connOpen(connection);
             * string query2 = "select * from loan where cid=" + Session["cid"].ToString();
             * Session["loannumber"] = dm.ReadRow(query, connection)["loannumber"].ToString();
             * dm.connClose(connection);   */
        }
    }
예제 #8
0
 public Logger(DatabaseManagement dm)
 {
     _dm = dm;
 }
예제 #9
0
        /// <summary>
        ///     数据库设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mniDatabaseSet_ItemClick(object sender, ItemClickEventArgs e)
        {
            var databaseManagementForm = new DatabaseManagement(DATABASE_TYPE.GasEmissionDB);

            databaseManagementForm.ShowDialog();
        }
예제 #10
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        int row = GridView1.Rows.Count;

        for (int i = 0; i < row; i++)
        {
            TextBox txt = (TextBox)GridView1.Rows[i].Cells[7].FindControl("TextBox1");
            txt.ReadOnly  = true;
            txt.BackColor = System.Drawing.Color.Yellow;
        }
        DatabaseManagement dm   = new DatabaseManagement();
        OracleConnection   conn = dm.dbaseConn();

        dm.connOpen(conn);

        int flag = 1;

        row = GridView1.Rows.Count;
        for (int i = 0; i < row; i++)
        {
            TextBox txt      = (TextBox)GridView1.Rows[i].Cells[7].FindControl("TextBox1");
            int     quantity = int.Parse(txt.Text);
            /*quantity*/

            int stock = int.Parse(GridView1.Rows[i].Cells[6].Text);

            if (quantity == 0)
            {
                string deletedpid   = GridView1.Rows[i].Cells[2].Text;
                string delete_query = "delete from dummytable where pid='" + deletedpid + "'";
                //dm.InsertRow(delete_query, conn);
                SqlDataSource1.DeleteCommand = delete_query;

                GridView1.DeleteRow(i);
                Label2.Text = "0";
                flag        = 0;
            }
            else if ((stock - quantity) <= 10)
            {
                GridView1.Rows[i].Cells[8].Text      = "minimun stock can be 10";
                GridView1.Rows[i].Cells[8].BackColor = System.Drawing.Color.Red;
                Label1.Text = (stock - quantity).ToString();
                flag        = 0;
            }
        }

        if (flag == 1)
        {
            int new_row = GridView1.Rows.Count;
            for (int i = 0; i < new_row; i++)
            {
                string  pid       = GridView1.Rows[i].Cells[2].Text;
                string  name      = GridView1.Rows[i].Cells[3].Text;
                TextBox txt       = (TextBox)GridView1.Rows[i].Cells[7].FindControl("TextBox1");
                int     quantity  = int.Parse(txt.Text);
                string  stock     = GridView1.Rows[i].Cells[6].Text;
                string  unitprice = GridView1.Rows[i].Cells[4].Text;
                string  date      = GridView1.Rows[i].Cells[5].Text;

                string order_product_query = "insert into order_product values('" + pid + "','" + name + "'," + int.Parse(unitprice) + "," + int.Parse(stock) + "," + quantity + ")";
                dm.InsertRow(order_product_query, conn);
                string shop_10_query = "insert into shop_10 values('" + Session["saleid"].ToString() + "','" + name + "'," + quantity + "," + unitprice + ")";
                dm.InsertRow(shop_10_query, conn);
                /*stock update*/
                int    update_stock = (int.Parse(stock) - quantity);
                string update_stock_product_6_query = "update product_6 set stock=" + update_stock + "where pid='" + pid + "'";
                Label1.Text = update_stock_product_6_query;
                dm.InsertRow(update_stock_product_6_query, conn);

                /*insert into database*/
            }

            string dateofsale  = GridView1.Rows[0].Cells[5].Text;
            string rep_4_query = "insert into rep_4 values('" + Session["rid"].ToString() + "','" + Session["saleid"].ToString() + "','" + Session["shopid"].ToString() + "',sysdate,'ok')";
            //Label1.Text = rep_4_query;
            dm.InsertRow(rep_4_query, conn);
            string sale_query = "insert into sale values('" + Session["saleid"].ToString() + "',to_char(sysdate,'DD-MON-YYYY'))";
            //Label2.Text = sale;
            dm.InsertRow(sale_query, conn);
            string schedule_11_query = "insert into schedule_11 values('" + Session["saleid"].ToString() + "',sysdate,'" + datofdelivery + "')";
            //  Label2.Text += " " + schedule_11_query;
            dm.InsertRow(schedule_11_query, conn);
            string shop_9_query = "insert into shop_9 values('" + Session["saleid"].ToString() + "','" + Session["shopid"].ToString() + "'," + cost + ",0)";
            //Label3.Text = shop_9_query;
            dm.InsertRow(shop_9_query, conn);
            string bonusinfo_query = "update bonusinfo set totalorder=(totalorder+" + cost + ") where rid='" + Session["rid"].ToString() + "'";
            //Label1.Text = bonusinfo_query;
            dm.InsertRow(bonusinfo_query, conn);
            /*insert into database*/

            /*bonus calculation*/
            string get_target = "select * from bonusinfo where rid='" + Session["rid"].ToString() + "'";
            string target     = dm.ReadRow(get_target, conn)["totaltarget"].ToString();
            string bonus_str  = dm.ReadRow(get_target, conn)["totalbonus"].ToString();
            string totalorder = dm.ReadRow(get_target, conn)["totalorder"].ToString();

            double final_total_order = double.Parse(totalorder) + cost;
            Label1.Text = final_total_order.ToString();
            double total_target = double.Parse(target);
            double bonus        = double.Parse(bonus_str);

            if (final_total_order >= total_target)
            {
                if (final_total_order == total_target)
                {
                    bonus = bonus + 500;
                }
                else
                {
                    bonus = bonus + ((final_total_order - total_target) * .05);
                }

                string update_bonusinfo = "update bonusinfo set totaltarget=" + (total_target + 50000) + ",totalbonus=" + bonus + " where rid='" + Session["rid"].ToString() + "'";
                Label1.Text = update_bonusinfo;
                dm.InsertRow(update_bonusinfo, conn);
            }

            string delete_saleid_query = "delete from dummytable where saleid='" + Session["saleid"].ToString() + "'";
            dm.InsertRow(delete_saleid_query, conn);

            /*notification starts here*/
            string confirm_notify = "insert into notification(ncounter,rid,shopid,saleid) values(2,'" + Session["rid"].ToString() + "','" + Session["shopid"].ToString() + "','" + Session["saleid"].ToString() + "')";
            dm.InsertRow(confirm_notify, conn);



            dm.connClose(conn);


            Response.Redirect("~/ComfirmOrder.aspx?" + Session["saleid"].ToString());
            //}
        }

        dm.connClose(conn);
    }
예제 #11
0
        public DatabaseDb AddDatabase(DatabaseModel database)
        {
            // Vérification du nom
            if (!RegularExpression.IsCorrectFileName(database.NomBD))
            {
                throw new DatabaseException("Le nom ne doit pas comporter des caractères spéciaux.");
            }

            // Le nom de la base de données doit être unique sur un serveur donné
            if (GetDatabase(database.ServerId, database.NomBD) != null)
            {
                throw new DatabaseException("Le nom de la base de données existe déjà.");
            }

            string             serverName         = "Serveur non trouvé";
            DatabaseServerUser databaseServerUser = null;

            try
            {
                // Obtention du serveur
                DatabaseServerName databaseServerName = db.DatabaseServerName.Find(database.ServerId);
                if (databaseServerName == null)
                {
                    return(null);
                }
                serverName = databaseServerName.Name;

                // Obtention du compte utilisateur du serveur
                ServerAccountService serverAccountService = new ServerAccountService(this.ServiceEpsiContext);
                databaseServerUser = serverAccountService.GetAccountByServerLogin(database.ServerId, database.UserLogin);
                if (databaseServerUser == null)
                {
                    return(null);
                }

                // Obtention du serveur réel : MySQL, SQL Server, ... avec son adresse IP
                DatabaseManagement management = DatabaseManagement.CreateDatabaseManagement(databaseServerName.Code, databaseServerName.Iplocale, databaseServerName.PortLocal);
                if (management == null)
                {
                    return(null);
                }

                // et céation de la base de données sur le serveur de BD
                management.CreateDatabase(database.NomBD, databaseServerUser.SqlLogin);
            }
            catch (Exception ex)
            {
                LogManager.GetLogger().Error(ex);
                throw new DatabaseException(string.Format("Erreur dans l'ajout de la base de données {0} sur le serveur '{1}', Erreur: {2}", database.ToString(), serverName, ex.Message));
            }

            // Ajout de la base de données dans le référentiel
            DatabaseDb databaseDB = new DatabaseDb
            {
                ServerId     = database.ServerId,
                NomBd        = database.NomBD,
                DateCreation = DateTime.Now,
                Commentaire  = database.Commentaire
            };

            db.DatabaseDb.Add(databaseDB);

            try
            {
                db.SaveChanges();

                // puis du créateur comme contributeur avec tous les droits
                DatabaseGroupUser databaseGroupUser = new DatabaseGroupUser
                {
                    DbId             = databaseDB.Id,
                    UserLogin        = databaseServerUser.UserLogin,
                    UserFullName     = database.UserFullName,
                    SqlLogin         = databaseServerUser.SqlLogin,
                    GroupType        = DatabaseValues.ADMINISTRATEUR,
                    AddedByUserLogin = databaseServerUser.UserLogin
                };
                db.DatabaseGroupUser.Add(databaseGroupUser);
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                if (!Exists(databaseDB.ServerId))
                {
                    return(null);
                }
                else
                {
                    LogManager.GetLogger().Error(ex);
                    throw new DatabaseException(string.Format("Erreur dans l'ajout de la base de données dans le référentiel", database.ToString()), ex);
                }
            }

            // Enregistrement dans les logs
            WriteLogs("BDD Création - " + string.Format("L'utilisateur '<b>{0}</b>' a créé la bdd '{1}' de type '{2}'", database.UserLogin, database.NomBD, database.ServerId));
            return(databaseDB);
        }
예제 #12
0
        public DatabaseGroupUser AddContributor(string userLogin, GroupUserModel groupUserModel)
        {
            string serverName = null;

            try
            {
                // Obtention de la base de données
                DatabaseDb databaseDB = GetDatabase(groupUserModel.DbId);
                if (databaseDB == null)
                {
                    return(null);
                }

                // Obtention du serveur
                DatabaseServerName databaseServerName = db.DatabaseServerName.Find(databaseDB.ServerId);
                if (databaseServerName == null)
                {
                    return(null);
                }
                serverName = databaseServerName.Name;

                // Obtention du serveur réel : MySQL, SQL Server, ... avec son adresse IP
                DatabaseManagement management = DatabaseManagement.CreateDatabaseManagement(databaseServerName.Code, databaseServerName.Iplocale, databaseServerName.PortLocal);
                if (management == null)
                {
                    return(null);
                }

                management.AddContributor(databaseDB.NomBd, groupUserModel.SqlLogin, groupUserModel.GroupType, groupUserModel.Password);
            }
            catch (Exception ex)
            {
                LogManager.GetLogger().Error(ex);
                throw new DatabaseException(string.Format("Erreur dans l'ajout du contributeur {0} sur le serveur '{1}'", groupUserModel.ToString(), serverName), ex);
            }

            DatabaseGroupUser contributor = new DatabaseGroupUser
            {
                DbId             = groupUserModel.DbId,
                SqlLogin         = groupUserModel.SqlLogin,
                AddedByUserLogin = userLogin,
                GroupType        = groupUserModel.GroupType,
                UserLogin        = groupUserModel.UserLogin,
                UserFullName     = groupUserModel.UserFullName
            };

            try
            {
                // Ajout du contributeur dans le groupe
                this.db.DatabaseGroupUser.Add(contributor);
                this.db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                LogManager.GetLogger().Error(ex);
                throw new DatabaseException(string.Format("Erreur dans l'ajout du contributeur {0} dans le référentiel", groupUserModel.ToString()), ex);
            }

            // Envoi du mail

            /*
             * if (userLoginSQL != null)
             *  contributor.UserLoginSQL = userLoginSQL;
             *
             *
             *  if (userEpsi != null)
             *  {
             *      contributor.UserEpsiFullName = userEpsi.Nom + " " + userEpsi.Prenom;
             *
             *      // Envoi du mail
             *      if (!string.IsNullOrWhiteSpace(userEpsi.Mail))
             *      {
             *          StringBuilder body = new StringBuilder();
             *          body.AppendFormat("Bonjour, </b><br /><br />Vous avez été ajouté comme contributeur dans la base de données '{0}' par l'utilisateur '{1}'", infos.Name, infos.Createur);
             *          if (accountAdded)
             *          {
             *              body.AppendFormat("<br /><br />Un compte a été créé sur le serveur '{0}' avec un mot de passe aléatoire.<br />", infos.Server.Name);
             *              body.Append("Vous devez vous connecter à <a href='https://ingenium.montpellier.epsi.fr/'>Ingénium</a> pour modifier le mot de passe de ce compte.");
             *          }
             *          body.Append("Connectez-vous à <a href='https://ingenium.montpellier.epsi.fr/'>Ingénium</a> pour voir vos base de données.");
             *          body.Append(@"</b><br /><br />L'administrateur réseau<br />EPSI Montpellier");
             *
             *          SendMail(userEpsi.Mail, "EPSI - Base de données - Ajout de contributeur", body.ToString());
             *      }
             *  }
             * }*/

            return(contributor);

            /*
             * {
             *  Message = message,
             *  Status = status,
             *  UserEpsiFullName = contributor.UserEpsiFullName,
             *  UserId = userId,
             *  LoginSQL = contributor.UserLoginSQL,
             *  GroupType = groupType,
             *  GroupTypeDescription = DatabaseService.GetGroupDescription(groupType)
             * });*/
        }