public ActionResult RegisterInfor(USERACCOUNT newUser)
 {
     if (ModelState.IsValid)
     {
         var t = dbContext.USERACCOUNTs.Where(x => x.EMAIL_USER == newUser.EMAIL_USER).FirstOrDefault();
         if (t != null)
         {
             ViewBag.Message = "Email is existing!";
         }
         else
         {
             USERACCOUNT userInfo = new USERACCOUNT();
             userInfo.ID_USER      = Guid.NewGuid().ToString("N");
             userInfo.NAME_USER    = newUser.NAME_USER;
             userInfo.PASS_USER    = newUser.PASS_USER;
             userInfo.ADDRESS_USER = newUser.ADDRESS_USER;
             userInfo.EMAIL_USER   = newUser.EMAIL_USER;
             userInfo.TEL_USER     = newUser.TEL_USER;
             userInfo.DISASBLE     = true;
             dbContext.USERACCOUNTs.Add(userInfo);
             dbContext.SaveChanges();
             return(RedirectToAction("Login", "Account"));
         }
     }
     return(View("Register"));
 }
Ejemplo n.º 2
0
        public ActionResult DeleteConfirmed(decimal id)
        {
            // confirming the deletion of a user
            USERACCOUNT uSERACCOUNT = db.USERACCOUNTs.Find(id); // finds the id

            db.USERACCOUNTs.Remove(uSERACCOUNT);                // deletes the whole account
            db.SaveChanges();                                   // saves changes
            return(RedirectToAction("Index"));                  // to the index of the table
        }
Ejemplo n.º 3
0
 [ValidateAntiForgeryToken] // protection for overposting data
 public ActionResult Edit([Bind(Include = "USERID,USERTYPE,FIRSTNAME,LASTNAME,PHONENUMBER,EMAILADDRESS,STREETNUMBER,POSTCODE,USERNAME,PASSWORD")] USERACCOUNT uSERACCOUNT)
 {
     // if statement for protection
     if (ModelState.IsValid)
     {
         db.Entry(uSERACCOUNT).State = EntityState.Modified; // gets the modified account
         db.SaveChanges();                                   // saves changes
         return(RedirectToAction("Index"));                  // return back to index
     }
     return(View(uSERACCOUNT));
 }
Ejemplo n.º 4
0
        public ActionResult EditUser(string id)
        {
            USERACCOUNT user = db.USERACCOUNTs.SingleOrDefault(n => n.ID_USER == id);

            if (user == null)
            {
                Response.StatusCode = 404;
                return(null);
            }

            return(View(user));
        }
Ejemplo n.º 5
0
        public ActionResult Create([Bind(Include = "USERID,USERTYPE,FIRSTNAME,LASTNAME,PHONENUMBER,EMAILADDRESS,STREETNUMBER,POSTCODE,USERNAME,PASSWORD")] USERACCOUNT uSERACCOUNT)
        {
            if (ModelState.IsValid) // checks if its valid for secucity reasons
            {
                //StringBuilder sbComments = new StringBuilder();
                //sbComments.Append(HttpUtility.HtmlEncode(uSERACCOUNT.)); // code for another security tried to implement
                db.USERACCOUNTs.Add(uSERACCOUNT);  // adds user account
                db.SaveChanges();                  // saves changes
                return(RedirectToAction("Index")); // goes back to index
            }

            return(View(uSERACCOUNT.ToString()));
        }
Ejemplo n.º 6
0
        // GET: UserAccounts/Edit/5
        public ActionResult Edit(decimal id)
        {
            // passes id to check if the id exists
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); // no id follwing the error
            }
            USERACCOUNT uSERACCOUNT = db.USERACCOUNTs.Find(id);

            if (uSERACCOUNT == null) // checks if there is the acc valid
            {
                return(HttpNotFound());
            }
            return(View(uSERACCOUNT)); // return the account for edit
        }
Ejemplo n.º 7
0
        // GET: UserAccounts/Details/5
        public ActionResult Details(decimal id)
        {
            // checks if id is null
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            USERACCOUNT uSERACCOUNT = db.USERACCOUNTs.Find(id);

            if (uSERACCOUNT == null) // checks if account exists
            {
                return(HttpNotFound());
            }
            return(View(uSERACCOUNT)); // returns the account in details
        }
Ejemplo n.º 8
0
        // GET: UserAccounts/Delete/5
        public ActionResult Delete(decimal id)
        {
            // if there is no id then the page will crush throwing the folowing error
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            USERACCOUNT uSERACCOUNT = db.USERACCOUNTs.Find(id);

            if (uSERACCOUNT == null)
            {
                return(HttpNotFound()); // if there is no account with that id
            }
            return(View(uSERACCOUNT));  // returns the account with the specific id for deletion
        }
Ejemplo n.º 9
0
        public ActionResult Login(string USERNAME, string PASSWORD)
        {
            USERACCOUNT existingUser = new USERACCOUNT(); //gets the username password

            existingUser.USERNAME = USERNAME;
            existingUser.PASSWORD = PASSWORD;

            if (existingUser.USERNAME == "acolonel" && existingUser.PASSWORD == "colonelaa")
            {
                return(Redirect("/Home/Index")); // redirects to internal url
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 10
0
 public ActionResult EditUser(string ID_USER, bool DISASBLE, HttpPostedFileBase fileUpload)
 {
     if (ModelState.IsValid)
     {
         try
         {
             USERACCOUNT model = db.USERACCOUNTs.Single(x => x.ID_USER == ID_USER);
             model.DISASBLE = DISASBLE;
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             return(RedirectToAction("Error", new { msg = ex.Message }));
         }
     }
     return(RedirectToAction("User"));
 }
 public string Post(USERACCOUNT USER)
 {
     try
     {
         string    query = @"EXACUTE ADD_USER " + USER.USERNAME + @"," + USER.PASSWORD + @"," + USER.ROLE;
         DataTable table = new DataTable();
         using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["FinalChallengeDB"].ConnectionString))
             using (var cmd = new SqlCommand(query, con))
                 using (var da = new SqlDataAdapter(cmd))
                 {
                     cmd.CommandType = CommandType.Text;
                     da.Fill(table);
                 }
         return("succsess");
     }
     catch (Exception)
     {
         return("falure");
     }
 }
Ejemplo n.º 12
0
        // GET: UserAccounts/Create
        public ActionResult Create()
        {
            // on create button click creates a new user id
            USERACCOUNT newUser = new USERACCOUNT();

            // checks the last user created
            var lastUser = db.USERACCOUNTs.OrderByDescending(x => x.USERID).FirstOrDefault();

            if (lastUser == null) // if there is no user it starts from the start
            {
                newUser.USERID = 1001;
            }
            else if (lastUser.USERID != 0) // or +1 to the last id created
            {
                newUser.USERID = lastUser.USERID + 1;
            }

            Convert.ToInt32(newUser.USERID); //makes the id an integer

            return(View(newUser));           //returns the id
        }
Ejemplo n.º 13
0
        //static public void Helper_Notify(Guid userID, string securableType, string securableID, XCommon.RIGHT right)
        static public void Helper_Notify(int userID, string securableType, string securableID, XCommon.RIGHT right)
        {
            XORCISMModel.XORCISMEntities model;
            model = new XORCISMModel.XORCISMEntities();

            string username = "";

            //username = model.USERS.FirstOrDefault(o => o.UserId == userID).UserName;
            username = model.USER.FirstOrDefault(o => o.UserID == userID).UserName;

            USERACCOUNT uia = null;
            //uia = model.USERACCOUNT.FirstOrDefault(o => o.UserID == userID);    //TODO review uniqueidentifier and uncomment

            int accountID;

            accountID = uia.ACCOUNT.AccountID;

            //List<RACISECURABLEINSTANCE> list;
            //list = model.RACISECURABLEINSTANCE.Where(o => o.SecurableType == securableType && o.SecurableID == securableID && o.AccountID == accountID && o.RACIValue == "I").ToList();

            string verb = "";

            switch (right)
            {
            case XCommon.RIGHT.CREATE:
                verb = "created";
                break;

            case XCommon.RIGHT.DELETE:
                verb = "deleted";
                break;

            case XCommon.RIGHT.MODIFY:
                verb = "modified";
                break;

            case XCommon.RIGHT.UNLOCK:
                verb = "unlocked";
                break;

            case XCommon.RIGHT.RELOAD:
                verb = "reloaded";
                break;
            }

            /*
             * foreach (RACISECURABLEINSTANCE instance in list)
             * {
             *  NOTIFICATION notification;
             *  notification = new XORCISMModel.NOTIFICATION();
             *  notification.CreatedDate = DateTimeOffset.Now;
             *  notification.UserID = instance.UserID;
             *
             *  switch (securableType)
             *  {
             *      case "TASK_ASSET":
             *          notification.NotificationMessage = string.Format("The asset #{0} has been {1} by user '{2}'", securableID, verb, username);
             *          break;
             *      case "TASK_USER":
             *          notification.NotificationMessage = string.Format("The user #{0} has been {1} by user '{2}'", securableID, verb, username);
             *          break;
             *      case "TASK_JOB":
             *          notification.NotificationMessage = string.Format("The user #{0} has been {1} by user '{2}'", securableID, verb, username);
             *          break;
             *  }
             *  notification.timestamp = DateTimeOffset.Now;
             *  model.NOTIFICATION.Add(notification);
             * }
             *
             * model.SaveChanges();
             */
        }
Ejemplo n.º 14
0
        private void FuncThread()
        {
            XORCISMEntities context;

            context = new XORCISMEntities();

            // Explicitly open the connection.
            //context.Connection.Open();



            // =================
            // Main polling loop
            // =================

            try
            {
                while (true)    //Infinite loop
                {
                    // =============================================================================
                    // PHASE 0 : Look in table SESSION and let's see if there is something to cancel
                    // =============================================================================

                    #region Phase0
                    //Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to cancel (those with status = 'ToCancel')");

                    string status;
                    status = XCommon.STATUS.TOCANCEL.ToString();

                    XORCISMModel.SESSION cancelSession;
                    cancelSession = context.SESSION.FirstOrDefault(s => s.Status == status);

                    if (cancelSession != null)
                    {
                        // ===============================
                        // Abort the Launch Session thread
                        // ===============================

                        if (m_ListRunningSessionThread.ContainsKey(cancelSession.SessionID) == true)
                        {
                            LaunchSessionThreadInfo info;
                            info = m_ListRunningSessionThread[cancelSession.SessionID];

                            Thread musCanceledThread;
                            musCanceledThread = info.Thread;

                            musCanceledThread.Abort(cancelSession.SessionID.ToString());

                            // ==============================
                            // Launch a Cancel Session thread
                            // ==============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching cancel session thread (sessionID={0})", cancelSession.SessionID));

                            cancelSession.Status = XCommon.STATUS.CANCELLING.ToString();

                            context.SaveChanges();

                            ParameterizedThreadStart ts;
                            ts = new ParameterizedThreadStart(FuncThreadCancelSession);

                            Thread thread;
                            thread = new Thread(ts);

                            thread.Start(info);
                        }
                        else
                        {
                            //Canceling after Manager crash/reboot
                            //Session is not in m_ListRunningSessionThread
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} must be canceled", cancelSession.SessionID));

                            //int accountID;
                            //accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;

                            // =============================
                            // Cancel the jobs on the agents
                            // =============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Cancelling jobs on agents", cancelSession.SessionID));

                            var jobs = from jc in context.JOB
                                       where jc.SessionID == cancelSession.SessionID
                                       select jc;

                            foreach (JOB J in jobs.ToList())
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Handling job {1}", cancelSession.SessionID, J.JobID));

                                // ====================================
                                // Contact the agent and cancel the job
                                // ====================================

                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Trying to contact the agent", cancelSession.SessionID));

                                try
                                {
                                    ServiceReferenceAgent.Service1Client service;
                                    service = new ServiceReferenceAgent.Service1Client();

                                    // TODO :
                                    // service.Endpoint.Address = bestAgent.IPAddress;

                                    service.CancelJob(J.JobID);

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : The agent has been successfully contacted", cancelSession.SessionID));
                                }
                                catch (Exception ex)
                                {
                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error contacting the agent. Exception = {1} {2}", cancelSession.SessionID, ex.Message, ex.InnerException));
                                    XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "CANCELSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
                                    //return;
                                }
                            }

                            // =============================
                            // Update table SESSION (Status)
                            // =============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Updating status in table SESSION to CANCELED", cancelSession.SessionID));
                            try
                            {
                                cancelSession.Status  = XCommon.STATUS.CANCELED.ToString();
                                cancelSession.DateEnd = DateTimeOffset.Now;

                                context.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error CANCELED. Exception = {1}", cancelSession.SessionID, ex.Message));
                                //return;
                            }
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Finished", cancelSession.SessionID));
                        }
                    }
                    #endregion Phase0

                    // =============================================================================
                    // PHASE 1 : Look in table SESSION and let's see if there is something to launch
                    // =============================================================================

                    Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to start (status IDLE)");    //DO NOT COMMENT THIS LINE

                    string Statut = XCommon.STATUS.IDLE.ToString();

                    var session = context.SESSION.FirstOrDefault(s => s.Status == Statut);

                    if (session != null)
                    {
                        int sessionID;
                        sessionID = session.SessionID;

                        //Check if the Account and User are still valid
                        USERACCOUNT user = null;
                        user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == session.UserID);
                        if (user.ACCOUNT.ValidUntilDate != null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
                        {
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for session {0}", sessionID));
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Changing session (sessionID={0}) to CANCELED", sessionID));

                            session.Status = XCommon.STATUS.CANCELED.ToString();
                            context.SaveChanges();
                        }
                        else
                        {
                            if (m_ListRunningSessionThread.ContainsKey(sessionID) == true)
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} is supposed to be launched but a thread is already running for this session !", sessionID));
                            }
                            else
                            {
                                // =======================
                                // Launch a session thread
                                // =======================

                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching session (sessionID={0})", sessionID));

                                session.Status = XCommon.STATUS.RUNNING.ToString();
                                context.SaveChanges();

                                ParameterizedThreadStart managerThreadStart;
                                managerThreadStart = new ParameterizedThreadStart(FuncThreadLaunchSession);

                                Thread thread;
                                thread = new Thread(managerThreadStart);

                                LaunchSessionThreadInfo info;
                                info = new LaunchSessionThreadInfo(sessionID, thread);

                                thread.Start(info);

                                // ========================
                                // Put it in the dictionary
                                // ========================

                                m_ListRunningSessionThread.Add(sessionID, info);
                            }
                        }
                    }

                    // ===================================================================================
                    // PHASE 2 : Look in table SESSIONCRON and let's see if we have to create new sessions
                    // ===================================================================================

                    Statut = XCommon.STATUS.IDLE.ToString();

                    var q = context.SESSIONCRON.Where(o => o.Status == Statut);

                    foreach (SESSIONCRON sessionCron in q.ToList())
                    {
                        if (sessionCron.DateEnd == null || sessionCron.DateEnd > DateTime.Now)
                        {
                            //Check if the Account and User are still valid
                            USERACCOUNT user = null;
                            user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == sessionCron.UserID);
                            if (user.ACCOUNT.ValidUntilDate != null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
                            {
                                //Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for entry {0} in table SESSIONCRON", sessionCron.SessionCronID));
                            }
                            else
                            {
                                CrontabSchedule schedule;
                                schedule = CrontabSchedule.Parse(sessionCron.CronExpression);

                                DateTimeOffset start = DateTimeOffset.Now;
                                DateTimeOffset end   = start + TimeSpan.FromDays(2 * 360);

                                var occurrence = schedule.GetNextOccurrences(start, end).GetEnumerator();
                                occurrence.MoveNext();
                                //                        Utils.Helper_Trace("MANAGER ENGINE", "SessionCron "+sessionCron.SessionCronID+" Next occurrence=" + occurrence.Current.DayOfWeek.ToString() + " " + occurrence.Current.Day.ToString() + "/" + occurrence.Current.Month.ToString() + "/" + occurrence.Current.Year.ToString() + " " + occurrence.Current.Hour.ToString() + "H" + occurrence.Current.Minute.ToString() + ":" + occurrence.Current.Second.ToString());

                                TimeSpan ts;
                                ts = occurrence.Current - start;
                                if (ts.TotalSeconds <= 5.0)
                                {
                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("Cron expression for entry {0} in table SESSIONCRON has triggered an execution", sessionCron.SessionCronID));

                                    // ================================
                                    // Extract and parse the parameters
                                    // ================================

                                    Dictionary <string, object> dicoParameters;
                                    try
                                    {
                                        MemoryStream ms;
                                        ms = new MemoryStream(sessionCron.Parameters);

                                        BinaryFormatter bf;
                                        bf = new BinaryFormatter();

                                        dicoParameters = (Dictionary <string, object>)bf.Deserialize(ms);
                                    }
                                    catch (Exception e)
                                    {
                                        Utils.Helper_Trace("MANAGER SERVICE", string.Format("Exception while deserializing parameters : {0}", e.Message));
                                        return;
                                    }

                                    int[] tabAssetID = null;
                                    if (dicoParameters["ASSETS"] != null)
                                    {
                                        tabAssetID = (int[])dicoParameters["ASSETS"];
                                    }

                                    // ================================
                                    // Add a new entry in table SESSION
                                    // ================================

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding an entry in table SESSION"));

                                    SESSION tmpSession = new SESSION();
                                    //xxx
                                    try
                                    {
                                        tmpSession.UserID            = sessionCron.UserID;
                                        tmpSession.Status            = XCommon.STATUS.IDLE.ToString();
                                        tmpSession.ServiceCategoryID = sessionCron.ServiceCategoryID;
                                        tmpSession.DateStart         = DateTimeOffset.Now;
                                        tmpSession.DateEnd           = null;
                                        tmpSession.Parameters        = sessionCron.Parameters;
                                        tmpSession.SessionCronID     = sessionCron.SessionCronID;

                                        context.SESSION.Add(tmpSession);

                                        context.SaveChanges();

                                        //xxx
                                    }
                                    catch (Exception ex)
                                    {
                                        //xxx

                                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
                                        throw ex;
                                    }

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SessionID = {0}", tmpSession.SessionID));

                                    // ============================================
                                    // Add several entries in table ASSETSESSION
                                    // ============================================

                                    if (tabAssetID != null)
                                    {
                                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding {0} entries in table ASSETSESSION", tabAssetID.Count()));
                                        try
                                        {
                                            foreach (int assetID in tabAssetID)
                                            {
                                                ASSETSESSION tmpAinS = new ASSETSESSION();
                                                tmpAinS.SESSION = tmpSession;
                                                tmpAinS.AssetID = assetID;
                                                context.ASSETSESSION.Add(tmpAinS);
                                            }
                                            context.SaveChanges();
                                        }
                                        catch (Exception ex)
                                        {
                                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message));
                                            throw ex;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // =====
                    // Sleep
                    // =====

                    Thread.Sleep(5000); //Hardcoded
                }
            }
            catch (ThreadAbortException exThreadAbort)
            {
                //int SessionId;
                //SessionId=Convert.ToInt32((string)exThreadAbort.ExceptionState);
                //XORCISMModel.SESSION musBeCanceledSession;
                //musBeCanceledSession=context.SESSION.SingleOrDefault(s => s.SessionID == SessionId);
                //if (musBeCanceledSession != null)
                //{
                //    musBeCanceledSession.Status = XCommon.STATUS.TOCANCEL.ToString();
                //    context.SaveChanges();
                //}
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadError in main polling loop : Exception = {0}", exThreadAbort.Message));
                //HARDCODED
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "ThreadError in XManager", "MyException = " + exThreadAbort.Message + " " + exThreadAbort.InnerException);
                return;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error in main polling loop : Exception = {0} {1}", ex.Message, ex.InnerException));
                //HARDCODED
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "Error in XManager", "MyException = " + ex.Message + " " + ex.InnerException);
                return;
            }
        }