void InsertSession()
        {
            if (!UnitOfWork.IsUnitOfWorkStarted ()) {
                using (var uow = UnitOfWork.Start()) {
                    var repo = new LocalSessionsRepository ();
                    var session = new SessionEntity()
                    {
                        title = "Test",
                    };
                    repo.Save(session);
                }
            }

            //sessions = repo.GetForSpeaker (speaker.SpeakerURI);
            //}
            //			using (var uow = UnitOfWork.Start())
            //			{
            //				var conference = new ConferenceEntity()
            //				{
            //					description = "description",
            //					//end = DateTime.Now,
            //					facebookUrl = "facebookUrl",
            //					name = "name",
            //					//Sessions = new List<SessionEntity>(),
            //				};
            //				uow.Session.SaveOrUpdate(conference);
            //			}
        }
Esempio n. 2
0
        public Result Logout(LogoutSessionRequest request, string adminId)
        {
            ValidationResult validationResult = _logoutSessionValidator.Validate(request);

            if (!validationResult.IsValid)
            {
                _logger.LogWarning($"Invlid LogoutSessionRequest. Admin {adminId}");
                return(Result.Fail(validationResult.Errors));
            }

            BaseSpecification <SessionEntity> specification = new BaseSpecification <SessionEntity>();

            specification.AddFilter(x => x.Id == request.SessionId);
            specification.AddFilter(x => x.UserId == request.UserId);

            SessionEntity session = _sessionRepository.SingleOrDefault(specification);

            if (session == null)
            {
                _logger.LogError($"Sesion does not exist. SessionId {request.SessionId}, Admin {adminId}");
                return(Result.Fail("no_session", "No Session"));
            }

            session.EndType = SessionEndTypes.AdminLogout;

            bool removeSessionResult = _sessionRepository.Remove(session);

            if (!removeSessionResult)
            {
                _logger.LogError($"Faild to remove session. SessionId {request.SessionId}, Admin {adminId}");
                return(Result.Fail("error", "Error"));
            }

            _logger.LogInformation($"Sessions logout. UserId {request.SessionId}, Admin {adminId}");

            return(Result.Ok());
        }
Esempio n. 3
0
        public RESTReplyData get_temporary_name(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();
            ResponseBody  respBody  = new ResponseBody();

            SessionEntity aSession = Sessions.Instance.UpdateSession(pReq.SenderKey);

            PersonNameGenerator png  = new PersonNameGenerator();
            PlaceNameGenerator  plng = new PlaceNameGenerator();

            DomainEntity newDomain = new DomainEntity()
            {
                PlaceName            = png.GenerateRandomFirstName() + "-" + plng.GenerateRandomPlaceName() + "-" + new Random().Next(500, 9000).ToString(),
                DomainID             = Guid.NewGuid().ToString(),
                IPAddrOfFirstContact = pReq.RemoteUser.ToString()
            };

            newDomain.API_Key = Tools.MD5Hash($":{newDomain.PlaceName}::{newDomain.DomainID}:{newDomain.IceServerAddr}");
            Domains.Instance.AddDomain(newDomain.DomainID, newDomain);

            respBody.Data = new bodyDomainResponse()
            {
                domain = new bodyDomainReplyData()
                {
                    id      = newDomain.DomainID,
                    name    = newDomain.PlaceName,
                    api_key = newDomain.API_Key
                }
            };
            replyData.SetBody(respBody, pReq);
            Context.Log.Debug("{0} Returning temporary domain: id={1}, name={2}",
                              _logHeader, newDomain.DomainID, newDomain.PlaceName);

            replyData.CustomOutputHeaders.Add("X-Rack-CORS", "miss; no-origin");
            replyData.CustomOutputHeaders.Add("Access-Control-Allow-Origin", "*");
            return(replyData);
        }
        /// <summary>
        /// Edits a Session
        ///</summary>
        /// <param name="Session"> Objeto Session a editar </param>
        public override int EditSession(SessionEntity entity_Session)
        {
            int result = 0;

            using (SqlConnection connection = new SqlConnection(SoftvSettings.Settings.Session.ConnectionString))
            {
                SqlCommand comandoSql = CreateCommand("Softv_SessionEdit", connection);

                AssingParameter(comandoSql, "@IdSession", entity_Session.IdSession);

                AssingParameter(comandoSql, "@IdUsuario", entity_Session.IdUsuario);

                AssingParameter(comandoSql, "@Token", entity_Session.Token);

                try
                {
                    if (connection.State == ConnectionState.Closed)
                    {
                        connection.Open();
                    }

                    result = int.Parse(ExecuteNonQuery(comandoSql).ToString());
                }
                catch (Exception ex)
                {
                    throw new Exception("Error updating Session " + ex.Message, ex);
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }
            return(result);
        }
Esempio n. 5
0
        public RESTReplyData user_get(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            SessionEntity aSession = Sessions.Instance.GetSession(pReq.SenderKey);

            PaginationInfo pagination = new PaginationInfo(pReq);

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                AccountFilterInfo  acctFilter  = new AccountFilterInfo(pReq);
                AccountScopeFilter scopeFilter = new AccountScopeFilter(pReq, aAccount);

                respBody.Data = new bodyUsersReply()
                {
                    users = Accounts.Instance.Enumerate(pagination, acctFilter, scopeFilter).Select(acct =>
                    {
                        bodyUser ret = new bodyUser()
                        {
                            username  = acct.Username,
                            accountid = acct.AccountID,
                            images    = acct.Images,
                        };
                        ret.location = BuildLocationInfo(acct);
                        return(ret);
                    }).ToArray()
                };
            }

            // Pagination fills the top level of the reply with paging info
            pagination.AddReplyFields(respBody);

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
 public override void ReleaseItemExclusive(HttpContext context, string id, object lockIdObject)
 {
     _log.DebugFormat("ReleaseItemExclusive({0})", id);
     LogExceptions("ReleaseItemExclusive()", () =>
     {
         SessionLockEntity lockId   = (SessionLockEntity)lockIdObject;
         SessionEntity sessionItems = new SessionEntity();
         sessionItems.Id            = id;
         sessionItems.ReleaseCount  = lockId.LockCount;
         sessionItems.Items         = lockId.Items;
         using (new LifetimeTimer(_log, "ReleaseItemExclusive", 25))
             using (var transaction = _datastore.BeginTransaction(_callSettings))
             {
                 SessionLockEntity sessionLock = SessionLockFromEntity(
                     transaction.Lookup(_lockKeyFactory.CreateKey(id), _callSettings));
                 if (sessionLock == null || sessionLock.LockCount != lockId.LockCount)
                 {
                     return; // Something else locked it in the meantime.
                 }
                 transaction.Upsert(ToEntity(sessionItems));
                 transaction.Commit(_callSettings);
             }
     });
 }
        public SessionEntity Map(string conferenceSlug, FullSessionDto dto)
        {
            var entity = new SessionEntity()
            {
                //Id = conferenceSlug + "/" + dto.slug,
                //TODO: conferenceId = conferenceSlug,
                description = dto.description,
                difficulty = dto.difficulty,
                end = dto.end,
                //links = dto.links,
                //prerequisites = dto.prerequisites,
                //resources = dto.resources,
                room = dto.room,
                sessionType = dto.sessionType,
                slug = dto.slug,
                start = dto.start,
                //subjects = dto.subjects,
                //tags = dto.tags,
                title = dto.title,
                twitterHashTag = dto.twitterHashTag,
            };

            return entity;
        }
Esempio n. 8
0
 public SessionEntity GetSession(string sessionId)
 {
     return(_sessionsReader.Get(SessionEntity.GetPk(), sessionId.ToSha256()));
 }
Esempio n. 9
0
        public void SessionEntitiesHaveAnId()
        {
            var entity = new SessionEntity();

            entity.Id.Should().BeGreaterOrEqualTo(0);
        }
Esempio n. 10
0
        public static void Run(SteamfitterContext context)
        {
            // sketch users
            var uAdministrator = new UserEntity {
                Id = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), Name = "admin user"
            };

            context.Users.Add(uAdministrator);

            // scenarios
            var scenario1 = new ScenarioEntity {
                Name = "First Scenario", Description = "My first scenario", CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow, DurationHours = 1
            };

            context.Scenarios.Add(scenario1);
            var scenario2 = new ScenarioEntity {
                Name = "Second Scenario", Description = "My second scenario", CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow, DurationHours = 2
            };

            context.Scenarios.Add(scenario2);
            var scenario3 = new ScenarioEntity {
                Name = "Third Scenario", Description = "My third scenario", CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow, DurationHours = 3
            };

            context.Scenarios.Add(scenario3);
            context.SaveChanges();
            // sessions
            var session1 = new SessionEntity {
                Name = "Session001", Description = "Session #1", ScenarioId = scenario1.Id, StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddMonths(1), DateCreated = DateTime.UtcNow, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), ExerciseId = Guid.Parse("453d394e-bf18-499b-9786-149b0f8d69ec"), Exercise = "RCC -E EM 2018", Status = SessionStatus.ready, OnDemand = false
            };

            context.Sessions.Add(session1);
            var session2 = new SessionEntity {
                Name = "Session002", Description = "Session #2", ScenarioId = scenario1.Id, StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddMonths(2), DateCreated = DateTime.UtcNow, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), ExerciseId = Guid.Parse("453d394e-bf18-499b-9786-149b0f8d69ec"), Exercise = "RCC -E EM 2018", Status = SessionStatus.ready, OnDemand = false
            };

            context.Sessions.Add(session2);
            context.SaveChanges();

            // //sessionVms  (or 5209fff8-8098-f1de-40c3-ac0eb1c8d515?)
            // var vm1 = new SessionVmEntity {SessionId =session1.Id, Vm = Guid.Parse("0539a863-ece6-4ca7-ae8d-f46a909526e9")};
            // context.SessionVms.Add(vm1);
            // context.SaveChanges();
            // VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9")

            // scenario #1 dispatchTasks
            var dispatchTask2 = new DispatchTaskEntity {
                Name = "Get host name", Description = "For scenario #1 get the host name from s3-vm", ScenarioId = scenario1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_process_run, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"CommandText\": \"CMD.EXE\", \"CommandArgs\": \"/c hostname\"}", ExpectedOutput = "DESKTOP-OM1GOK7", TriggerCondition = TaskTrigger.Manual, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask2);
            var dispatchTask2b = new DispatchTaskEntity {
                Name = "Run netstat -an", Description = "For sceanrion #1 run netstat -an against all of the vm's", ScenarioId = scenario1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_process_run, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"CommandText\": \"CMD.EXE\", \"CommandArgs\": \"/c netstat -an\"}", ExpectedOutput = "This will never work!", TriggerCondition = TaskTrigger.Manual, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask2b);
            // sceanrio #2 dispatchTasks
            var dispatchTaskC1 = new DispatchTaskEntity {
                Name = "Parent Task #1", Description = "Read the test file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testGet.txt\"}", ExpectedOutput = "This is the text from the TEST file.", TriggerCondition = TaskTrigger.Manual, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC1);
            var dispatchTaskC1b = new DispatchTaskEntity {
                Name = "Success Task", Description = "Read the success file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testSuccess.txt\"}", ExpectedOutput = "This is the text from the SUCCESS file.", TriggerTask = dispatchTaskC1, TriggerCondition = TaskTrigger.Success, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC1b);
            var dispatchTaskC3 = new DispatchTaskEntity {
                Name = "Failure Task", Description = "Read the failure file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testFailure.txt\"}", ExpectedOutput = "This is the text from the FAILURE file.", TriggerTask = dispatchTaskC1, TriggerCondition = TaskTrigger.Failure, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC3);
            var dispatchTaskC4 = new DispatchTaskEntity {
                Name = "Completion Task", Description = "Read the completion file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testCompletion.txt\"}", ExpectedOutput = "This is the text from the COMPLETION file.", TriggerTask = dispatchTaskC1, TriggerCondition = TaskTrigger.Completion, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC4);
            var dispatchTaskC5 = new DispatchTaskEntity {
                Name = "Expiration Task", Description = "Read the expiration file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testExpiration.txt\"}", ExpectedOutput = "This is the text from the EXPIRATION file.", TriggerTask = dispatchTaskC1, TriggerCondition = TaskTrigger.Expiration, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC5);
            var dispatchTaskC6 = new DispatchTaskEntity {
                Name = "Delayed Task", Description = "Read the delay file from s3-vm", ScenarioId = scenario2.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testDelay.txt\"}", ExpectedOutput = "This is the text from the DELAY file.", TriggerTask = dispatchTaskC4, TriggerCondition = TaskTrigger.Completion, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, DelaySeconds = 10, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTaskC6);
            // session #1 dispatchTasks
            var dispatchTask1 = new DispatchTaskEntity {
                Name = "Parent Task", Description = "Parent Task #1a", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testGet.txt\"}", ExpectedOutput = "This is the text from the TEST file.", TriggerCondition = TaskTrigger.Manual, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask1);
            var dispatchTask1b = new DispatchTaskEntity {
                Name = "Success Task", Description = "Success Task #1b", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testSuccess.txt\"}", ExpectedOutput = "This is the text from the SUCCESS file.", TriggerTask = dispatchTask1, TriggerCondition = TaskTrigger.Success, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask1b);
            context.DispatchTasks.Add(dispatchTask2b);
            var dispatchTask3 = new DispatchTaskEntity {
                Name = "Failure Task", Description = "Failure Task #3", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testFailure.txt\"}", ExpectedOutput = "This is the text from the FAILURE file.", TriggerTask = dispatchTask1, TriggerCondition = TaskTrigger.Failure, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask3);
            var dispatchTask4 = new DispatchTaskEntity {
                Name = "Completion Task", Description = "Completion Task #4", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testCompletion.txt\"}", ExpectedOutput = "This is the text from the COMPLETION file.", TriggerTask = dispatchTask1, TriggerCondition = TaskTrigger.Completion, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask4);
            var dispatchTask5 = new DispatchTaskEntity {
                Name = "Expiration Task", Description = "Expiration Task #5", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testExpiration.txt\"}", ExpectedOutput = "This is the text from the EXPIRATION file.", TriggerTask = dispatchTask1, TriggerCondition = TaskTrigger.Expiration, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask5);
            var dispatchTask6 = new DispatchTaskEntity {
                Name = "Delayed Task", Description = "Delayed Task #6", SessionId = session1.Id, ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testDelay.txt\"}", ExpectedOutput = "This is the text from the DELAY file.", TriggerTask = dispatchTask4, TriggerCondition = TaskTrigger.Completion, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, DelaySeconds = 10, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask6);
            // independent task
            var dispatchTask1c = new DispatchTaskEntity {
                Name = "Independent Task", Description = "Independent Task #1c", ApiUrl = "stackstorm", Action = TaskAction.guest_file_read, InputString = "{\"VmGuid\": \"42313053-c2e6-42af-cf2a-6db9f791794a\", \"Username\": \"Developer\", \"Password\": \"develop@1\", \"GuestFilePath\": \"C:\\\\Users\\\\Developer\\\\testGet.txt\"}", ExpectedOutput = "This is the text from the TEST file.", TriggerCondition = TaskTrigger.Manual, ExpirationSeconds = 0, IntervalSeconds = 0, Iterations = 0, CreatedBy = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), UserId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), DateCreated = DateTime.UtcNow
            };

            context.DispatchTasks.Add(dispatchTask1c);
            context.SaveChanges();

            // // DispatchTaskResults
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask1.Id, VmId = Guid.Parse("0539a863-ece6-4ca7-ae8d-f46a909526e9"), VmName = "S3-VM2", Status = TaskStatus.queued, InputString = "copy test1.txt success.txt", ExpectedOutput = "Copied", ExpirationSeconds = 61, Iterations = 1, IntervalSeconds = 0, DateCreated = DateTime.Now.AddMinutes(-33)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.queued, InputString = "copy test2.txt success.txt", ExpectedOutput = "Oh boy!", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-43)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.succeeded, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ActualOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-53)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.failed, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ActualOutput = "Failure", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-55)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.succeeded, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ActualOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-153)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.sent, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-155)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.error, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-156)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.queued, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-157)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.expired, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-158)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.pending, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-159)
            });
            context.DispatchTaskResults.Add(new DispatchTaskResultEntity {
                DispatchTaskId = dispatchTask2.Id, VmId = Guid.Parse("9fd3c38e-58b0-4af1-80d1-1895af91f1f9"), VmName = "S3-VM3", Status = TaskStatus.cancelled, InputString = "copy test.txt success.txt", ExpectedOutput = "Completed", ExpirationSeconds = 62, Iterations = 2, IntervalSeconds = 120, DateCreated = DateTime.Now.AddMinutes(-175)
            });
            context.SaveChanges();

            Console.WriteLine("Seed data completed");
        }
Esempio n. 11
0
 public async Task CloseSession(SessionEntity session, string reason)
 {
     await _sessionsWriter.DeleteAsync(session.PartitionKey, session.RowKey);
 }
Esempio n. 12
0
        public async Task LogoutAsync(SessionEntity session)
        {
            await _sessionsWriter.DeleteAsync(session.PartitionKey, session.RowKey);

            await _clientSessionsClient.DeleteSessionIfExistsAsync(session.Token);
        }
 public SessionStateStoreData GetItemImpl(bool exclusive,
                                          HttpContext context, string id, out bool locked,
                                          out TimeSpan lockAge, out object lockId,
                                          out SessionStateActions actions)
 {
     try
     {
         using (new LifetimeTimer(_log, "GetItemImpl", 25))
             using (var transaction = _datastore.BeginTransaction(_callSettings))
             {
                 // Look up both entities in datastore.
                 var entities = transaction.Lookup(new Key[]
                 {
                     _sessionKeyFactory.CreateKey(id),
                     _lockKeyFactory.CreateKey(id)
                 }, _callSettings);
                 SessionLockEntity sessionLock = SessionLockFromEntity(entities[1]);
                 if (sessionLock == null || sessionLock.ExpirationDate < DateTime.UtcNow)
                 {
                     // No such session.
                     lockAge = TimeSpan.Zero;
                     locked  = false;
                     lockId  = null;
                     actions = SessionStateActions.None;
                     return(null);
                 }
                 SessionEntity sessionItems = SessionFromEntity(id, entities[0]);
                 sessionLock.Items = sessionItems.Items;
                 locked            = sessionLock.LockCount > sessionItems.ReleaseCount;
                 lockAge           = locked ? DateTime.UtcNow - sessionLock.DateLocked
                 : TimeSpan.Zero;
                 lockId  = sessionLock;
                 actions = SessionStateActions.None;
                 if (locked)
                 {
                     return(null);
                 }
                 if (exclusive)
                 {
                     // Lock the session.
                     sessionLock.LockCount      = sessionItems.ReleaseCount + 1;
                     sessionLock.DateLocked     = DateTime.UtcNow;
                     sessionLock.ExpirationDate =
                         DateTime.UtcNow.AddMinutes(sessionLock.TimeOutInMinutes);
                     transaction.Upsert(ToEntity(sessionLock));
                     transaction.Commit(_callSettings);
                     locked = true;
                 }
                 return(Deserialize(context, sessionItems.Items,
                                    sessionLock.TimeOutInMinutes));
             }
     }
     catch (Exception e)
     {
         _log.Error("GetItemImpl()", e);
         locked  = true;
         lockAge = TimeSpan.Zero;
         lockId  = 0;
         actions = SessionStateActions.None;
         return(null);
     }
 }
Esempio n. 14
0
 /// <summary>
 /// Abstract method to update Session
 /// </summary>
 public abstract int EditSession(SessionEntity entity_Session);
Esempio n. 15
0
 public int?AddSession(SessionEntity objSession)
 {
     return(Session.Add(objSession));
 }
Esempio n. 16
0
 public static int Add(SessionEntity objSession)
 {
     int result = ProviderSoftv.Session.AddSession(objSession);
     return result;
 }
Esempio n. 17
0
 /// <summary>
 /// Abstract method to add Session
 ///  /summary>
 /// <param name="Session"></param>
 /// <returns></returns>
 public abstract int AddSession(SessionEntity entity_Session);
 public SessionData ToData(SessionEntity entity) =>
 Mapper.Map <SessionData>(entity);
Esempio n. 19
0
 public SessionBuilder SetSessionEntity(SessionEntity sessionEntity)
 {
     SessionEntity = sessionEntity;
     return(this);
 }
Esempio n. 20
0
 public static int Edit(SessionEntity objSession)
 {
     int result = ProviderSoftv.Session.EditSession(objSession);
     return result;
 }
Esempio n. 21
0
 public ValueTask SaveSessionAsync(SessionEntity session)
 {
     return(_sessionsWriter.InsertOrReplaceAsync(session));
 }
Esempio n. 22
0
        public RESTReplyData domain_heartbeat(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            SessionEntity aSession = Sessions.Instance.UpdateSession(pReq.SenderKey);

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                try
                {
                    // Since the body has a lot of optional fields, we need to pick
                    //    through what's sent so we only set what was sent.
                    JObject requestData = pReq.RequestBodyJSON();
                    JObject domainStuff = (JObject)requestData["domain"];
                    string  apiKey      = (string)domainStuff["api_key"];

                    // Context.Log.Debug("{0} domain_heartbeat. Received {1}", _logHeader, pReq.RequestBody);
                    if (VerifyDomainAccess(aDomain, pReq, apiKey, out string oFailureReason))
                    {
                        Tools.SetIfSpecified <string>(domainStuff, "version", ref aDomain.Version);
                        Tools.SetIfSpecified <string>(domainStuff, "protocol", ref aDomain.Protocol);
                        Tools.SetIfSpecified <string>(domainStuff, "network_address", ref aDomain.NetworkAddr);
                        Tools.SetIfSpecified <string>(domainStuff, "automatic_networking", ref aDomain.NetworkingMode);
                        Tools.SetIfSpecified <bool>(domainStuff, "restricted", ref aDomain.Restricted);

                        Tools.SetIfSpecified <int>(domainStuff, "capacity", ref aDomain.Capacity);
                        Tools.SetIfSpecified <string>(domainStuff, "description", ref aDomain.Description);
                        Tools.SetIfSpecified <string>(domainStuff, "maturity", ref aDomain.Maturity);
                        Tools.SetIfSpecified <string>(domainStuff, "restriction", ref aDomain.Restriction);
                        JArray hosts = (JArray)domainStuff["hosts"];
                        if (hosts != null)
                        {
                            aDomain.Hosts = domainStuff["hosts"].ToObject <string[]>();
                        }
                        JArray tags = (JArray)domainStuff["tags"];
                        if (tags != null)
                        {
                            aDomain.Tags = domainStuff["tags"].ToObject <string[]>();
                        }

                        JObject heartbeat = (JObject)domainStuff["heartbeat"];
                        if (heartbeat != null)
                        {
                            Tools.SetIfSpecified <int>(heartbeat, "num_users", ref aDomain.NumUsers);
                            Tools.SetIfSpecified <int>(heartbeat, "num_anon_users", ref aDomain.AnonUsers);
                            aDomain.TotalUsers = aDomain.NumUsers + aDomain.AnonUsers;
                            // TODO: what to do with user_hostnames
                        }

                        aDomain.TimeOfLastHeartbeat = DateTime.UtcNow;
                        aDomain.LastSenderKey       = pReq.SenderKey;

                        aDomain.Updated();
                    }
                    else
                    {
                        Context.Log.Error("{0} domain_heartbeat with bad authorization. domainID={1}",
                                          _logHeader, domainID);
                        respBody.RespondFailure(oFailureReason);
                        replyData.Status = (int)HttpStatusCode.Unauthorized;
                    }
                }
                catch (Exception e)
                {
                    Context.Log.Error("{0} domain_heartbeat: Exception processing body: {1}", _logHeader, e.ToString());
                    respBody.RespondFailure("exception processing body", e.ToString());
                    replyData.Status = (int)HttpStatusCode.BadRequest;
                }
            }
            else
            {
                Context.Log.Error("{0} domain_heartbeat: unknown domain. Returning 404", _logHeader);
                respBody.RespondFailure("no such domain");
                replyData.Status = (int)HttpStatusCode.NotFound; // this will trigger a new temporary domain name
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 23
0
 public ValueTask ProlongateSessionAsync(SessionEntity session)
 {
     session.ExpirationDate = DateTime.UtcNow.AddMinutes(_expirationTimeInMins);
     return(_sessionsWriter.InsertOrReplaceAsync(session));
 }
Esempio n. 24
0
        public async Task <LoginResponse> FindByLogin(LoginDto user)
        {
            var baseUser          = new UserEntity();
            var failLoginResponse = new LoginResponse()
            {
                authenticated = false
            };

            if (user != null && !string.IsNullOrWhiteSpace(user.Email))
            {
                baseUser = await _repository1.FindByLogin(user.Email);

                if ((baseUser == null) || (baseUser.ds_senha != user.Senha))
                {
                    if (baseUser == null)
                    {
                        failLoginResponse.message = _localizer["userNotFound"].Value;
                    }
                    else
                    {
                        failLoginResponse.message = _localizer["passNotFound"].Value;
                    }
                }
                else
                {
                    var language = await GetLanguage((int)baseUser.cd_cliente);

                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
                    System.Threading.Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo(language);

                    var activeSessions = await CheckSession(baseUser);

                    if (baseUser.vl_max_sessoes - activeSessions <= 0)
                    {
                        failLoginResponse.message = _localizer["sessionLimit"].Value;
                    }
                    else
                    {
                        var identity = new ClaimsIdentity(
                            new GenericIdentity(baseUser.cd_codigo.ToString()),
                            new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //jti O Id do Token
                            new Claim(JwtRegisteredClaimNames.UniqueName, user.Email),
                        }
                            );
                        DateTime createDate     = DateTime.Now;
                        DateTime expirationDate = createDate + TimeSpan.FromSeconds(_tokenConfigurations.Seconds);
                        var      handler        = new JwtSecurityTokenHandler();
                        string   token          = CreateToken(identity, createDate, expirationDate, handler);
                        var      session        = new SessionEntity()
                        {
                            cd_usuario          = baseUser.cd_codigo,
                            st_ativo            = true,
                            ds_ip               = "10.0.0.13",
                            ds_estacao_trabalho = "webUser",
                            txt_hash            = token,
                            txt_data_login      = DateTime.Now.ToString()
                        };
                        var rSession = await InserteSession(session);

                        user.sessionId = rSession.cd_codigo;

                        return(SucessObject(createDate, expirationDate, token, user));
                    }
                }
            }
            else
            {
                failLoginResponse.message = _localizer["authenticateFailed"].Value;
            }
            return(failLoginResponse);
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            //
            List <String> lstUriAction = request.Headers.To.ToString().Split('/').ToList();
            String        Action       = lstUriAction.Last().ToUpper();
            String        Module       = lstUriAction[lstUriAction.Count() - 2].ToUpper();

            if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
                return(null);
            }
            else
            {
                // Check to see if there is an Authorization in the header, otherwise throw a 401
                if (WebOperationContext.Current.IncomingRequest.Headers["Authorization"] == null)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                    throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                }

                else // Decode the header, check password
                {
                    string encodedUnamePwd = "";
                    if (Module == "USUARIO" && Action == "LOGON")
                    {
                        encodedUnamePwd = GetEncodedCredentialsFromHeader();
                        if (!string.IsNullOrEmpty(encodedUnamePwd))
                        {
                            // Decode the credentials
                            byte[] decodedBytes = null;
                            try
                            {
                                decodedBytes = Convert.FromBase64String(encodedUnamePwd);
                            }
                            catch (FormatException)
                            {
                                return(false);
                            }

                            string credentials = ASCIIEncoding.ASCII.GetString(decodedBytes);

                            // Validate User and Password
                            string[]      authParts  = credentials.Split(':');
                            Usuario       objUsuario = new Usuario();
                            UsuarioEntity objUsr     = Usuario.GetusuarioByUserAndPass(authParts[0], authParts[1]);
                            if (objUsr == null)
                            {
                                WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                            }
                        }
                    }
                    else
                    {
                        encodedUnamePwd = GetTokenFromHeader();
                        if (!string.IsNullOrEmpty(encodedUnamePwd))
                        {
                            List <SessionEntity> objSessionEntity = Session.GetAll();
                            if (!objSessionEntity.Any(x => x.Token == encodedUnamePwd))
                            {
                                WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                            }
                            else
                            {
                                SessionEntity objSession = objSessionEntity.Where(x => x.Token == encodedUnamePwd).FirstOrDefault();
                                UsuarioEntity objUsr     = Usuario.GetOne(objSession.IdUsuario);
                                if (!(lstInvaliAction.Where(x => (Action.StartsWith(x) || lstInvaliAction.Contains(Action))).Any()))
                                {
                                    List <SecutityEntity> lstSecutityEntity = Secutity.GetPagedList(1, 99999, Globals.SerializeTool.Serialize <SecutityEntity>(new SecutityEntity()
                                    {
                                        Module = Module
                                    })).ToList();
                                    if (lstSecutityEntity.Any(x => x.Action == Action))
                                    {
                                        SecutityEntity objSecutity = lstSecutityEntity.Where(x => x.Action == Action).FirstOrDefault();
                                        if (objSecutity != null)
                                        {
                                            List <PermisoEntity> lstPermisos = Permiso.GetXml(Globals.SerializeTool.Serialize <PermisoEntity>(new PermisoEntity()
                                            {
                                                IdRol = objUsr.IdRol
                                            })).ToList();
                                            PermisoEntity objPermisos = lstPermisos.Where(x => x.Module.ModulePath.ToUpper() == Module.ToUpper()).ToList().FirstOrDefault();

                                            if (objPermisos != null)
                                            {
                                                switch (objSecutity.Permision)
                                                {
                                                case "S":
                                                {
                                                    return(null);
                                                }

                                                case "A":
                                                {
                                                    if (objPermisos.OptAdd == true)
                                                    {
                                                        return(null);
                                                    }
                                                    else
                                                    {
                                                        WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                                        throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                                    }
                                                }

                                                case "D":
                                                {
                                                    if (objPermisos.OptDelete == true)
                                                    {
                                                        return(null);
                                                    }
                                                    else
                                                    {
                                                        WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                                        throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                                    }
                                                }

                                                case "U":
                                                {
                                                    if (objPermisos.OptUpdate == true)
                                                    {
                                                        return(null);
                                                    }
                                                    else
                                                    {
                                                        WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                                        throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                                    }
                                                }

                                                default:
                                                {
                                                    WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                                    throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                                }
                                                }
                                            }
                                            else
                                            {
                                                WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                                throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\"");
                                        throw new WebFaultException <string>("Acceso no autorizado, favor de validar autenticación", HttpStatusCode.Unauthorized);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 26
0
 public SessionEntity GetSessionByOriginToken(string sessionId)
 {
     return(_sessionsReader.Get(SessionEntity.GetPk(), sessionId.ToSha256().ToBase64()));
 }
Esempio n. 27
0
 public async Task <SessionEntity> InserteSession(SessionEntity session)
 {
     return(await _repository2.InsertAsync(session));
 }
Esempio n. 28
0
 public void SaveSessionData(SessionEntity session)
 {
     _sessionData.SaveData(session);
 }
Esempio n. 29
0
 public int?UpdateSession(SessionEntity objSession)
 {
     return(Session.Edit(objSession));
 }
Esempio n. 30
0
 public static bool DataValid(IAlarmClock alarmClock, SessionEntity sessionEntity) => DateTime.Compare(alarmClock.Now, sessionEntity.ValidUntil) < 0;