private void HandleClient(object cObj) { TcpClient Client = (TcpClient)cObj; Tmp.Entry Entry = new Tmp.Entry(); GlobalVar.nStream = Client.GetStream(); byte[] Header = new byte[8]; Entry.IP = Client.Client.RemoteEndPoint.ToString().Split(':')[0]; GlobalFunc.Write("Client [{0}] - Connected", Entry.IP); using (PoorManStream pmStream = new PoorManStream(GlobalVar.nStream)) { using (EndianIO MainIO = new EndianIO(Header, EndianStyle.BigEndian)) { if (GlobalVar.nStream.Read(Header, 0, 8) != 8) { GlobalFunc.WriteError(ConsoleColor.Red, "[SERVER]", "Header recieved unexpected size!"); Client.Close(); } uint Command = MainIO.Reader.ReadUInt32(); int PacketSize = MainIO.Reader.ReadInt32(); byte[] Buffer = new byte[PacketSize]; using (EndianIO WriterIO = new EndianIO(pmStream, EndianStyle.BigEndian)) { using (EndianIO ReaderIO = new EndianIO(Buffer, EndianStyle.BigEndian) { Writer = new EndianWriter(pmStream, EndianStyle.BigEndian) }) { if (pmStream.Read(Buffer, 0, PacketSize) != PacketSize) { GlobalFunc.WriteError(ConsoleColor.Red, "[SERVER]", "Packet recieved unexpected size!"); Client.Close(); } switch (Command) { case (uint)cmdCode.GET_SESSION: SESSION.Get(ref Entry, WriterIO, ReaderIO); break; case (uint)cmdCode.GET_STATUS: STATUS.Get(ref Entry, WriterIO, ReaderIO); break; case (uint)cmdCode.GET_CHAL_RESPONSE: break; case (uint)cmdCode.UPDATE_PRESENCE: PRESENCE.Update(ref Entry, WriterIO, ReaderIO); break; case (uint)cmdCode.GET_XOSC: break; case (uint)cmdCode.GET_INFO: break; case (uint)cmdCode.SND_SPOOFY: break; case (uint)cmdCode.GET_MESSAGE: break; case (uint)cmdCode.GET_PATCHES: break; case (uint)cmdCode.GET_GUIDE_INFO: break; default: break; } } } } } }
public SESSION Login(string json) { var dict = Convertor.FromJsonToDict2(json); var inst = Convertor.FromDictionaryToObject <SESSION>(dict); var res = SESSION.Login(inst.UserID, null); return(res); }
public ActionResult DeleteConfirmed(decimal id) { SESSION sESSION = db.SESSIONS.Find(id); db.SESSIONS.Remove(sESSION); db.SaveChanges(); return(RedirectToAction("Index")); }
public HandlerDbTaskCalculate(ID_TASK idTask = ID_TASK.UNKNOWN) : base() { _Session = new SESSION() { m_Id = -1, m_currIdPeriod = ID_PERIOD.UNKNOWN, m_currIdTimezone = ID_TIMEZONE.UNKNOWN, m_curOffsetUTC = int.MinValue, m_rangeDatetime = new DateTimeRange() }; IdTask = idTask; }
public ActionResult Edit([Bind(Include = "SESSION_CODE,START_TIME,ACTIVITY_ID,ROOM_ID,REF_NO")] SESSION sESSION) { if (ModelState.IsValid) { db.Entry(sESSION).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ACTIVITY_ID = new SelectList(db.ACTIVITIES, "ACTIVITY_ID", "NAME", sESSION.ACTIVITY_ID); ViewBag.REF_NO = new SelectList(db.CUSTOMERS, "REF_NO", "NAME", sESSION.REF_NO); ViewBag.ROOM_ID = new SelectList(db.ROOMS, "ROOM_ID", "ROOM_NAME", sESSION.ROOM_ID); return(View(sESSION)); }
// GET: Sessions/Details/5 public ActionResult Details(decimal id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SESSION sESSION = db.SESSIONS.Find(id); if (sESSION == null) { return(HttpNotFound()); } return(View(sESSION)); }
public void updateSession(int id_user, Guid token) { try { SESSION userToken = new SESSION(); userToken.ID_USER = id_user; userToken.TOKEN = token; userToken.CREATION_DATE = DateTime.Now; userToken.LAST_CONNECT_DATE = DateTime.Now; } catch { throw new Exception("Impossible de créer la session."); } }
// GET: Sessions/Edit/5 public ActionResult Edit(decimal id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SESSION sESSION = db.SESSIONS.Find(id); if (sESSION == null) { return(HttpNotFound()); } ViewBag.ACTIVITY_ID = new SelectList(db.ACTIVITIES, "ACTIVITY_ID", "NAME", sESSION.ACTIVITY_ID); ViewBag.REF_NO = new SelectList(db.CUSTOMERS, "REF_NO", "NAME", sESSION.REF_NO); ViewBag.ROOM_ID = new SelectList(db.ROOMS, "ROOM_ID", "ROOM_NAME", sESSION.ROOM_ID); return(View(sESSION)); }
public bool Rec_Session(Survey _surv) { int surveyID = Convert.ToInt32(_surv.S_ID); int Q_ID = Convert.ToInt32(_surv.ID); using (EventrixDBDataContext db = new EventrixDBDataContext()) { try { int _query = (from res in db.SESSIONs where res.S_Id.Equals(surveyID) select res).Count(); if (_query == 0) //Create New Answer { SESSION toinsert = new SESSION(); toinsert.S_Id = _surv.S_ID; toinsert.Very_Dissatisfied = _surv.veryDissatisfied; toinsert.Dissatisfied = _surv.Dissatisfied; toinsert.Neutral = _surv.Neutral; toinsert.Very_Satisfied = _surv.VerySatisfied; toinsert.Satisfied = _surv.Satisfied; db.SESSIONs.InsertOnSubmit(toinsert); db.SubmitChanges(); return(true); } else //Update Record { SESSION query = (from res in db.SESSIONs where res.S_Id.Equals(surveyID) select res).First(); query.Very_Dissatisfied += _surv.veryDissatisfied; query.Dissatisfied += _surv.Dissatisfied; query.Neutral += _surv.Neutral; query.Satisfied += _surv.Satisfied; query.Very_Satisfied += _surv.VerySatisfied; db.SubmitChanges(); return(true); } } catch (Exception) { return(false); } }; }
public string addSession(int id_user) { try { Guid token = Guid.NewGuid(); SESSION userToken = new SESSION(); userToken.ID_USER = id_user; userToken.TOKEN = token; userToken.CREATION_DATE = DateTime.Now; userToken.LAST_CONNECT_DATE = DateTime.Now; Context.SESSIONs.Add(userToken); Context.SaveChanges(); return(token.ToString()); } catch { throw new Exception("Impossible de créer la session."); } }
public string addSession(int id_user) { try { Guid token = Guid.NewGuid(); SESSION userToken = new SESSION(); userToken.ID_USER = id_user; userToken.TOKEN = token; userToken.CREATION_DATE = DateTime.Now; userToken.LAST_CONNECT_DATE = DateTime.Now; Context.SESSIONs.Add(userToken); Context.SaveChanges(); return token.ToString(); } catch { throw new Exception("Impossible de créer la session."); } }
//public void Run(string target, int jobID, string policy, string strategy) public void Run(string data, int jobID, int AccountID) { Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " Entering Run()"); Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Creating an instance of CenzicParser for AccountID=" + AccountID.ToString())); CenzicParser CenzicParser = new CenzicParser(data, AccountID, jobID); inerror = false; if (!inerror) { Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + jobID + " Parsing the data")); CenzicParser.parse(); Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + jobID + " End of data processing")); Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Updating job {0} status to FINISHED", jobID)); CenzicParser.UpdateJob(jobID); XORCISMEntities model = new XORCISMEntities(); var xJob = from j in model.JOB where j.JobID == jobID select j; JOB xJ = xJob.FirstOrDefault(); xJ.Status = XCommon.STATUS.FINISHED.ToString(); Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "Changing the session to ServiceCategoryID=2"); var xSession = from s in model.SESSION where s.SessionID == xJ.SessionID select s; SESSION xS = xSession.FirstOrDefault(); xS.ServiceCategoryID = 2; model.SaveChanges(); } else { Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " inerror"); } Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " Leaving Run()"); }
public void Run(string data, int jobID, int AccountID) { //WARNING: OLD CODE, should be reviewed and revised Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Entering Run()"); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Creating an instance of NessusParser for AccountID=" + AccountID.ToString())); NessusParser NessusParser = new NessusParser(data, AccountID, jobID); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Parsing the data")); NessusParser.parse(); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Updating job status to FINISHED"); XORCISMEntities model = new XORCISMEntities(); var xJob = from j in model.JOB where j.JobID == jobID select j; JOB xJ = xJob.FirstOrDefault(); xJ.Status = XCommon.STATUS.FINISHED.ToString(); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Changing the session to ServiceCategoryID=1"); var xSession = from s in model.SESSION where s.SessionID == xJ.SessionID select s; SESSION xS = xSession.FirstOrDefault(); xS.ServiceCategoryID = 1; model.SaveChanges(); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("End of data processing")); Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Leaving Run()"); }
public void Run(string data, int jobID, int AccountID) { Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Entering Run()"); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Creating an instance of SkipfishImportParser for AccountID=" + AccountID.ToString())); SkipfishImportParser SkipfishImportParser = new SkipfishImportParser(data, AccountID, jobID); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Parsing the data")); SkipfishImportParser.parse(); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Updating job status to FINISHED"); XORCISMEntities model = new XORCISMEntities(); var xJob = from j in model.JOB where j.JobID == jobID select j; JOB xJ = xJob.FirstOrDefault(); xJ.Status = XCommon.STATUS.FINISHED.ToString(); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Changing the session to ServiceCategoryID=2"); var xSession = from s in model.SESSION where s.SessionID == xJ.SessionID select s; SESSION xS = xSession.FirstOrDefault(); xS.ServiceCategoryID = 2; //HARDCODED model.SaveChanges(); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("End of data processing")); Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Leaving Run()"); }
private void FuncThreadCancelSession(object context) { LaunchSessionThreadInfo info; info = (LaunchSessionThreadInfo)context; int sessionID; sessionID = info.SessionID; XORCISMEntities model = new XORCISMEntities(); SESSION session; session = model.SESSION.SingleOrDefault(o => o.SessionID == 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} : THREADCANCELSESSION : Cancelling jobs on agents", sessionID)); foreach (JOB J in info.ListJob) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Handling job {1}", sessionID, J.JobID)); // ==================================== // Contact the agent and cancel the job // ==================================== Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Trying to contact the agent", sessionID)); try { ServiceReferenceAgent.Service1Client service; service = new ServiceReferenceAgent.Service1Client(); // TODO : // service.Endpoint.Address = bestAgent.IPAddress; service.CancelJob(J.JobID); } catch (Exception ex) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error contacting the agent. Exception = {1} {2}", sessionID, ex.Message, ex.InnerException)); //HARDCODED XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "THREADCANCELSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException); return; } Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : The agent has been successfully contacted", sessionID)); } // ============================= // Update table SESSION (Status) // ============================= Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Updating status in table SESSION to CANCELED", sessionID)); var mySession = from Sess in model.SESSION where Sess.SessionID == sessionID select Sess; SESSION MySession = mySession.ToList().First(); MySession.Status = XCommon.STATUS.CANCELED.ToString(); MySession.DateEnd = DateTimeOffset.Now; model.SaveChanges(); try { m_ListRunningSessionThread.Remove(sessionID); } catch (Exception ex) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error m_ListRunningSessionThread.Remove. Exception = {1}", sessionID, ex.Message)); return; } Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Finished", sessionID)); }
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; } }
private void FuncThreadLaunchSession(object context) { LaunchSessionThreadInfo info; info = (LaunchSessionThreadInfo)context; int sessionID; sessionID = info.SessionID; XORCISMEntities model = new XORCISMEntities(); SESSION session; session = model.SESSION.SingleOrDefault(o => o.SessionID == sessionID); int accountID; accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID; // =========================================== // Determine the providers that we have to use // =========================================== var category = (from sessions in model.SESSION where sessions.SessionID == sessionID select sessions.ServiceCategoryID).First(); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : ServiceCategoryID is {1} AccountID is {2}", sessionID, category.Value, accountID)); var ListProvider = from provider in model.PROVIDER where provider.ServiceCategoryID == category && provider.PROVIDERSFORACCOUNT.Any(o => o.AccountID == accountID && o.ValidUntil >= DateTimeOffset.Now) select provider.ProviderID; List <int> listProviderID; listProviderID = ListProvider.ToList <int>(); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session will use {1} providers", sessionID, listProviderID.Count)); int nbjoberror = 0; if (listProviderID.Count > 0) { // ================================ // Add several entries in table JOB // ================================ var ListAssetInSession = from AinS in model.ASSETSESSION where AinS.SessionID == sessionID select AinS.AssetSessionID; Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session involves {1} assets", sessionID, ListAssetInSession.Count())); int count; count = ListAssetInSession.Count() * listProviderID.Count; Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Adding {1} entries in table JOB", sessionID, count)); var param = from o in model.SESSION where o.SessionID == sessionID select o.Parameters; if (ListAssetInSession.Count() != 0) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 1", sessionID)); foreach (int AinSID in ListAssetInSession) { foreach (int providerID in listProviderID) { try { JOB job = new JOB(); job.AssetSessionID = AinSID; job.ProviderID = providerID; job.DateStart = DateTimeOffset.Now; job.Status = XCommon.STATUS.IDLE.ToString(); job.Parameters = param.First(); job.SessionID = sessionID; model.JOB.Add(job); //model.AddToJOB(job); //model.SaveChanges(); info.ListJob.Add(job); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID)); } catch (Exception e1) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob1 " + e1.Message + " " + e1.InnerException, sessionID)); } } } model.SaveChanges(); } else { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 2", sessionID)); switch ((int)category.Value) { case 10: //nmap discovery Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : nmap discovery", sessionID)); break; case 11: Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import nessus", sessionID)); break; case 14: Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import netsparker", sessionID)); break; case 15: Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import acunetix", sessionID)); break; default: return; } foreach (int providerID in listProviderID) { try { JOB job = new JOB(); job.AssetSessionID = null; job.ProviderID = providerID; job.DateStart = DateTimeOffset.Now; job.Status = XCommon.STATUS.IDLE.ToString(); job.Parameters = param.First(); job.SessionID = sessionID; //model.JOB.AddObject(job); model.JOB.Add(job); model.SaveChanges(); info.ListJob.Add(job); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID)); } catch (Exception e1) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob2 " + e1.Message + " " + e1.InnerException, sessionID)); } } } //model.SaveChanges(); // ========================================= // Dispatch the jobs on the available agents // ========================================= Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Dispatching jobs on agents", sessionID)); foreach (JOB J in info.ListJob) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Handling job {1}", sessionID, J.JobID)); // ====================================================== //TODO Get the agent with the lowest load (loadbalancing) // ====================================================== //TODO /* * var agent = from Ag in model.AGENT * where Ag.Status == "ENABLED" * select Ag; * if (agent == null) * { * Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There is no agent with status ENABLED", sessionID)); * return; * } */ //TODO /* * var bestAgent = agent.ToList().OrderBy(c => c.Load).First(); * bestAgent.Load++; * * Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The best agent for this job is at {1} ({2})", sessionID, bestAgent.AgentID, bestAgent.IPAddress)); */ // ==================================== // Contact the agent and launch the job // ==================================== Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Trying to contact the agent", sessionID)); try { ServiceReferenceAgent.Service1Client service; service = new ServiceReferenceAgent.Service1Client(); // TODO : // service.Endpoint.Address = bestAgent.IPAddress; // TODO service.LaunchJob((Guid)session.UserID, J.JobID); } catch (Exception ex) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Error contacting the agent. Exception = {1}", sessionID, ex.Message)); //HARDCODED XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "THREADLAUNCHSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException); return; } Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The agent has been successfully contacted", sessionID)); // ===================================== //TODO Update table JOB (column AgentID) // ===================================== Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : TODO Updating table JOB (AgentID column)", sessionID)); //TODO //J.AgentID = bestAgent.AgentID; //TODO: TryCatch model.SaveChanges(); } // ================================= // Wait until all jobs have finished // ================================= Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Waiting until all jobs have finished", sessionID)); try { bool bFinished = false; do { Thread.Sleep(10000); //HARDCODED bFinished = true; nbjoberror = 0; // Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There are {1} jobs in this session", sessionID, info.ListJob.Count.ToString())); var myCurrentSession = from Sess in model.SESSION where Sess.SessionID == sessionID select Sess; SESSION CurrentSession = myCurrentSession.ToList().First(); foreach (JOB J in info.ListJob) { int AllJobs = 0; // ========================== // Get the status of this job // ========================== var MyJob = from MyJobs in model.JOB where MyJobs.JobID == J.JobID select MyJobs.Status; string jobStatus = (string)MyJob.ToList().First(); if (jobStatus != XCommon.STATUS.FINISHED.ToString() && jobStatus != XCommon.STATUS.ERROR.ToString()) { bFinished = false; break; } else { if (jobStatus == XCommon.STATUS.ERROR.ToString()) { nbjoberror++; } AllJobs++; } int pourcent = (100 / (int)MyJob.Count()) * AllJobs; // CurrentSession.Status = pourcent + "%"; //model.SaveChanges(); } }while (bFinished == false); } catch (ThreadAbortException ex) { Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Thread has been aborted", sessionID)); Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadAbortException : Exception = {0}", ex.Message)); return; } Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs have finished ({1} Errors)", sessionID, nbjoberror)); } // ============================= // Update table SESSION (Status) // ============================= Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Updating status in table SESSION", sessionID)); var mySession = from Sess in model.SESSION where Sess.SessionID == sessionID select Sess; SESSION MySession = mySession.ToList().First(); string additionalmailMessage = string.Empty; //Dealing with jobs in error if (info.ListJob.Count == nbjoberror) { //TODO xxx MySession.Status = XCommon.STATUS.ERROR.ToString(); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs in error: xxx", sessionID)); //TODO xxx } else { MySession.Status = XCommon.STATUS.FINISHED.ToString(); } MySession.DateEnd = DateTimeOffset.Now; model.SaveChanges(); // ============ // Notification // ============ //TODO //XCommon.Utils.Helper_Notify(session.UserID.Value, "TASK_JOB", sessionID.ToString(), XCommon.RIGHT.MODIFY); //TODO /* * string mailMessage = "Hello "+ session.aspnet_Membership.USERS.UserName +". Your Hackenaton session " + sessionID + " ("+ MySession.SERVICECATEGORY.ServiceCategoryName +") is completed with the status: "+ MySession.Status+". Assets scanned: "; //HARDCODED * var myAssets = from assets in model.ASSET * join assetinsess in model.ASSETSESSION on assets.AssetID equals assetinsess.AssetID * where assetinsess.SessionID == sessionID * select assets; * foreach (ASSET ass in myAssets) * { * //TODO ipaddressIPv4 * mailMessage += ass.ipaddressIPv4 + " "; * } * mailMessage += "Completed in " + string.Format("{0:00}:{1:00}:{2:00}", (MySession.DateEnd.Value - MySession.DateStart.Value).Hours, (MySession.DateEnd.Value - MySession.DateStart.Value).Minutes, (MySession.DateEnd.Value - MySession.DateStart.Value).Seconds); * mailMessage +=". Visit the Hackenaton website to display the Report."; * mailMessage += additionalmailMessage; * XCommon.Utils.Helper_SendEmail(session.aspnet_Membership.Email, "Hackenaton scan finished", mailMessage); //HARDCODED */ m_ListRunningSessionThread.Remove(sessionID); Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Finished", sessionID)); }
partial void UpdateSESSION(SESSION instance);
static void Main() { //******************************************************* // WARNING: SORRY, theXploiter is not public... //******************************************************* XORCISMEntities model = new XORCISMEntities(); int mySessionID = 3555; //TODO: TEST var thesession = from s in model.SESSION where s.SessionID == mySessionID select s; SESSION mysession = thesession.FirstOrDefault(); int ServiceCategory = (int)mysession.ServiceCategoryID; Console.WriteLine("ServiceCategory=" + ServiceCategory); var myjobs = from j in model.JOB where j.SessionID == mySessionID select j; /* * foreach (JOB job in myjobs.ToList()) * { * Console.WriteLine("job=" + job.JobID); * var myinfos = from i in model.INFORMATION * where i.JobID == job.JobID * select i; * * foreach (INFORMATION info in myinfos.ToList()) * { * Console.WriteLine(info.Title); * * } * } */ switch (ServiceCategory) { case 1: { //Vulnerability Assessment break; } case 2: { //Web Application Assessment break; } default: { break; } } //Retrieve the known exploits for the VULNERABILITYFOUND //Analyze the gathered information //Launch the appropriate pentests for each ENDPOINT }
partial void DeleteSESSION(SESSION instance);
public SESSION GetSESIONID(int id) { SESSION sesion = this.context.GetSESIONID(id); return(sesion); }
//public CompositeType GetDataUsingDataContract(CompositeType composite) //{ // if (composite == null) // { // throw new ArgumentNullException("composite"); // } // if (composite.BoolValue) // { // composite.StringValue += "Suffix"; // } // return composite; //} public int CreateSession(int serviceCategoryID, Guid userID, byte[] parameters, Decimal PeasCount, Decimal PeasValue) { //Where Magic happens Utils.Helper_Trace("MANAGER SERVICE", "Entering CreateSession()"); Utils.Helper_Trace("MANAGER SERVICE", string.Format("ServiceCategoryID = {0}", serviceCategoryID)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("UserID = {0}", userID.ToString())); Dictionary<string, object> dicoParameters; try { MemoryStream ms; ms = new MemoryStream(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 -1; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("Size of parameters = {0} bytes", parameters.Length)); int[] tabAssetID = null; int MaxPages; string FileName = string.Empty; string nmapAddress = string.Empty; string cronExpression = string.Empty; string sip = string.Empty; string extrange = string.Empty; string policy = string.Empty; string strategie = string.Empty; switch (serviceCategoryID) //TODO Hardcoded { case 1: // Vulnerability Assessment tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 2: //WAS (Web Application Scanning) tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 3: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 3"); break; case 4: //PCI DSS tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = "PCI DSS"; strategie = "Compliance PCI DSS"; //(string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 5: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 5"); break; case 6: // VOIP Scanner tabAssetID = (int[])dicoParameters["ASSETS"]; sip = (string)dicoParameters["SIP"]; extrange = (string)dicoParameters["EXTRANGE"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); break; case 7: // Web Anti-malware Monitoring tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; MaxPages = (int)dicoParameters["MaxPages"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:MaxPages = {0}", MaxPages)); break; case 8: // Web Site Monitoring tabAssetID = (int[])dicoParameters["ASSETS"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); break; case 9: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 9"); break; case 10: // Discovery nmapAddress = (string)dicoParameters["TARGET"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Target = {0}", nmapAddress)); break; case 11: case 12: case 13: // Import case 14: case 15: FileName = (string)dicoParameters["FILENAME"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Import File : Filename = {0}", FileName)); break; case 16: //Information Gathering (OSINT) tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; } XORCISMEntities context = new XORCISMEntities(); // =============================================== // Add a new entry in table SESSION or SESSIONCRON // =============================================== int id; if (cronExpression == "") { // ================================ // Add a new entry in table SESSION // ================================ Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSION")); SESSION tmpSession = new SESSION(); //Price try { tmpSession.UserID = userID; tmpSession.Status = XCommon.STATUS.IDLE.ToString(); tmpSession.ServiceCategoryID = serviceCategoryID; tmpSession.DateEnd = null; tmpSession.DateStart = DateTimeOffset.Now; tmpSession.Parameters = parameters; //Price context.SESSION.Add(tmpSession); context.SaveChanges(); //Price } catch (Exception ex) { /* USER user; user = context.USERS.SingleOrDefault(u => u.UserId == userID); ACCOUNT userAccount; userAccount = context.USERACCOUNT.SingleOrDefault(o => o.UserID == user.UserId).ACCOUNT; //Price */ Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); throw ex; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionID = {0}", tmpSession.SessionID)); //Random random = new Random(); try { // tmpSession.SessionID = tmpSession.SessionID + random.Next(20, 200); // context.SaveChanges(); } catch (Exception ex) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error random SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); } Utils.Helper_Trace("MANAGER SERVICE", string.Format("NewRandomSessionID = {0}", tmpSession.SessionID)); id = tmpSession.SessionID; // ============================================ // Add several entries in table ASSETSESSION // ============================================ if (tabAssetID != null) { Utils.Helper_Trace("MANAGER SERVICE", 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 SERVICE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message)); throw ex; } } } else { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSIONCRON")); SESSIONCRON tmpSessionCron = new SESSIONCRON(); //Price try { tmpSessionCron.UserID = userID; tmpSessionCron.CronExpression = cronExpression; tmpSessionCron.Parameters = parameters; tmpSessionCron.Status = XCommon.STATUS.IDLE.ToString(); tmpSessionCron.ServiceCategoryID = serviceCategoryID; tmpSessionCron.DateStart = DateTimeOffset.Now; //TODO Non il faut que ce soit les dates de start/end du cron A VOIR TODO tmpSessionCron.DateEnd = null; //Price context.SESSIONCRON.Add(tmpSessionCron); context.SaveChanges(); } catch (Exception ex) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSIONCRON : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); throw ex; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionCronID = {0}", tmpSessionCron.SessionCronID)); id = tmpSessionCron.SessionCronID; } Utils.Helper_Trace("MANAGER SERVICE", "Leaving CreateSession()"); // Finished return id; }
void Start() { Stopwatch sw = new Stopwatch(); sw.Start(); // timeVector setup for (int FRAME = 0; FRAME < Number.frames; FRAME++) { timeVector[FRAME] = (float)FRAME / 144; } // scene setup FPS_text = GameObject.Find("Canvas/FPS").GetComponent <TextMeshProUGUI>(); cursorMaterial = Resources.Load("UnlitColor") as Material; timeText = GameObject.Find("Canvas/Time").GetComponent <TextMeshProUGUI>(); sessionText = GameObject.Find("Canvas/Session").GetComponent <TextMeshProUGUI>(); // session setup float[,] GetBufferData(int port) { UnityBuffer unityBuffer = new UnityBuffer(); if (unityBuffer.connect(host: "127.0.0.1", port: port)) { print("connected: " + port.ToString()); unityBuffer.header = unityBuffer.getHeader(); float[,] data = unityBuffer.getFloatData(0, unityBuffer.header.nSamples - 1); return(data); } else { print("connection failed..."); return(new float[0, 0]); } } void printArrayDimensions(float[,] array) { print(array.GetLength(0)); print(array.GetLength(1)); } // reshape method List <Vector2> reshapeTrajectory(List <float[, ]> trajectoryData, int TRIAL, float xMod, float yMod) { List <Vector2> trajectoryToUse = new List <Vector2>(); for (int FRAME = 0; FRAME < Number.frames; FRAME++) { Vector2 position = new Vector2(); for (int AXIS = 0; AXIS < Number.axes; AXIS++) { //print(TRIAL.ToString() + ":" + FRAME.ToString() + ":" + AXIS.ToString()); if (AXIS == 0) { position[AXIS] = trajectoryData[AXIS][TRIAL, FRAME] + xMod; } else { position[AXIS] = trajectoryData[AXIS][TRIAL, FRAME] + yMod; } } trajectoryToUse.Add(position); } return(trajectoryToUse); } void AddCursors(int[] ports, string parentName, CursorType cursorType, float xMod, float yMod, float[,] target_positions, GameObject grandParent) { GameObject parent = new GameObject(name: parentName); parent.transform.parent = grandParent.transform; // get trajectories List <float[, ]> trajectory = new List <float[, ]>(); foreach (var port in ports) { //print(port); trajectory.Add(GetBufferData(port)); //printArrayDimensions(trajectory[trajectory.Count - 1]); } // build cursors for (int TRIAL = 0; TRIAL < Number.trials; TRIAL++) { List <Vector2> cursorTrajectory = reshapeTrajectory(trajectory, TRIAL, xMod, yMod); Color colorToUse = colors[(int)target_positions[TRIAL, 0] - 1]; float randomValue = UnityEngine.Random.Range(.25f, 1); colorToUse.r = colorToUse.r * randomValue; colorToUse.g = colorToUse.g * randomValue; colorToUse.b = colorToUse.b * randomValue; GameObject SpawnCursorObject() { switch (cursorType) { case CursorType.cursor: GameObject cursorObject1 = PlaneObject.Create(width: Sizes.cursor, length: Sizes.cursor, widthSegments: 1, lengthSegments: 1).gameObject; cursorObject1.GetComponent <Renderer>().material = cursorMaterial; cursorObject1.GetComponent <Renderer>().material.color = colorToUse; return(cursorObject1); case CursorType.gaze: GameObject cursorObject2 = Create.Polygon(position: Vector3.zero, rotation: new Vector3(-90, 0, 0), radius: Sizes.gaze, edgeThickness: .1f, nSegments: Defaults.nSegementsCircle, color: colorToUse, sortingOrder: 1); return(cursorObject2); default: return(new GameObject()); } } GameObject cursorObject = SpawnCursorObject(); cursorObject.name = "cursor." + TRIAL.ToString(); cursorObject.transform.parent = parent.transform; cursors.Add(new Cursor(gameObject: cursorObject, trajectory: cursorTrajectory)); } } // add target positions void DrawTargets(float xMod, float yMod, string parentName, GameObject grandParent) { GameObject targets = new GameObject(name: parentName); targets.transform.parent = grandParent.transform; for (int TARGET = 0; TARGET < Number.targetPositions; TARGET++) { GameObject target = Create.Polygon(position: new Vector3(targetPositions[TARGET].x + xMod, 0, targetPositions[TARGET].y + yMod), rotation: new Vector3(-90, 0, 0), radius: Sizes.target, edgeThickness: .1f, nSegments: Defaults.nSegementsCircle, color: Color.white, //colors[TARGET], sortingOrder: 2); target.name = "target." + TARGET.ToString(); target.transform.parent = targets.transform; } } //int[] sessionsToUse = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; int[] sessionsToUse = new int[] { 12, 13, 14, 15, 16, 17 }; int sessionCount = 0; void prepareSession(int SESSION) { print("***************************************************************"); print("SESSION: " + SESSION.ToString()); sessionText.text = "S" + Labels.session[SESSION]; GameObject grandParentObject = new GameObject(name: Labels.session[SESSION]); float yModToUse = 0; for (int CONTROL = 0; CONTROL < Number.control; CONTROL++) { DrawTargets(xMod[CONTROL], yModToUse, "targets." + Labels.control[CONTROL], grandParentObject); } float[,] target_positions_solo = GetBufferData(Ports.target_positions_solo); AddCursors(Ports.P1, "P1", CursorType.cursor, xMod[0], yModToUse, target_positions_solo, grandParentObject); AddCursors(Ports.P2, "P2", CursorType.cursor, xMod[0], yModToUse, target_positions_solo, grandParentObject); AddCursors(Ports.P1_gaze_solo, "P1_gaze_solo", CursorType.gaze, xMod[0], yModToUse, target_positions_solo, grandParentObject); AddCursors(Ports.P2_gaze_solo, "P2_gaze_solo", CursorType.gaze, xMod[0], yModToUse, target_positions_solo, grandParentObject); float[,] target_positions_joint = GetBufferData(Ports.target_positions_joint); AddCursors(Ports.joint, "joint", CursorType.cursor, xMod[1], yModToUse, target_positions_joint, grandParentObject); AddCursors(Ports.P1_gaze_joint, "P1_gaze_joint", CursorType.gaze, xMod[1], yModToUse, target_positions_joint, grandParentObject); AddCursors(Ports.P2_gaze_joint, "P2_gaze_joint", CursorType.gaze, xMod[1], yModToUse, target_positions_joint, grandParentObject); } prepareSession(1); void StartOBSrecording() { var proc = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo // get process by window name - super dodge - also cannot run Pathly from unity { FileName = @"C:\Program Files (x86)\obs-studio\OBSCommand_v1.5.4\OBSCommand\OBSCommand.exe", Arguments = "/startrecording", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); } StartOBSrecording(); print(sw.Elapsed.Seconds); }
public MainPage(IWebDriver session) : base(session) { SESSION.Navigate().GoToUrl(URL); }
partial void InsertSESSION(SESSION instance);