Example #1
0
        static void Main(string[] args)
        {
            var console = new ClientConsole();

            //Note: Using the singleton version
            //var configuration = Singleton.Configuration.Instance;
            //var client = Singleton.Quilt4NetClient.Instance;
            //var sessionHandler = Singleton.Session.Instance;
            //var issueHandler = Singleton.Issue.Instance;

            //Note: Using the created instance version
            var configuration = new Configuration();
            var client = new Quilt4NetClient(configuration);
            var sessionHandler = new SessionHandler(client);
            var issueHandler = new IssueHandler(sessionHandler);

            //Note: Config in code
            //configuration.Enabled = true; //Turn the entire quilt4Net feature on or off.
            //configuration.ProjectApiKey = "9XG02ZE0BR1OI75IVX446B59M13RKBR_"; //TODO: Replace with your own ProjectApiKey.
            //configuration.ApplicationName = "MyOverrideApplication"; //Overrides the name of the assembly
            //configuration.ApplicationVersion = "MyOverrideVersion"; //Overrides the version of the assembly
            //configuration.UseBuildTime = false; //If true, separate 'versions' for each build of the assembly will be logged, even though the version number have not changed.
            //configuration.Session.Environment = "Test"; //Use dev, test, production or any other verb you like to filter on.
            //configuration.Target.Location = "http://localhost:29660"; //Address to the target service.
            //configuration.Target.Timeout = new TimeSpan(0, 0, 60);

            console.WriteLine("Connecting to quilt4 server " + configuration.Target.Location, OutputLevel.Information);

            sessionHandler.SessionRegistrationStartedEvent += Session_SessionRegistrationStartedEvent;
            sessionHandler.SessionRegistrationCompletedEvent += SessionSessionRegistrationCompletedEvent;
            sessionHandler.SessionEndStartedEvent += Session_SessionEndStartedEvent;
            sessionHandler.SessionEndCompletedEvent += Session_SessionEndCompletedEvent;
            issueHandler.IssueRegistrationStartedEvent += Issue_IssueRegistrationStartedEvent;
            issueHandler.IssueRegistrationCompletedEvent += Issue_IssueRegistrationCompletedEvent;
            client.WebApiClient.AuthorizationChangedEvent += WebApiClient_AuthorizationChangedEvent;
            client.WebApiClient.WebApiRequestEvent += WebApiClientWebApiRequestEvent;
            client.WebApiClient.WebApiResponseEvent += WebApiClient_WebApiResponseEvent;            

            _rootCommand = new RootCommand(console);
            _rootCommand.RegisterCommand(new UserCommands(client));
            _rootCommand.RegisterCommand(new ProjectCommands(client));
            _rootCommand.RegisterCommand(new InvitationCommands(client));
            _rootCommand.RegisterCommand(new SessionCommands(sessionHandler));
            _rootCommand.RegisterCommand(new IssueCommands(issueHandler));
            _rootCommand.RegisterCommand(new SettingCommands(client));
            _rootCommand.RegisterCommand(new ServiceCommands(client));
            _rootCommand.RegisterCommand(new WebCommands(issueHandler, client.WebApiClient));
            new CommandEngine(_rootCommand).Run(args);

            sessionHandler.Dispose();
        }
Example #2
0
        public override void Initialize() {
            base.Initialize();

            SessionFactory = new SessionFactory(this);

            Routes["/"]["GET"] = new ResourceResponder("twin-rc.index.html","text/html; charset=utf-8");
            Routes["/ide"]["GET"] = new ResourceResponder("twin-rc.ide.html","text/html; charset=utf-8");
            Routes["/ide.jar"]["GET"] = new ResourceResponder("twin-rc.twin-ide.jar","application/x-java-archive");
            Routes["/status"]["GET"] = new JSONHandler(Sessions.Status);

            Routes["/session"]["POST"] = new JSONHandler(Sessions.Create);
            Routes["/session/:session"]["GET"] = new JSONHandler(Sessions.GetCapabilities);
            Routes["/session/:session"]["DELETE"] = new JSONHandler(Sessions.Delete);

            Routes["/session/:session/element/active"]["GET"] = new SessionHandler(Elements.GetFocused);
            Routes["/session/:session/element/active"]["POST"] = new SessionHandler(Elements.SetFocused);

            Routes["/session/:session/attachment"]["POST"] = new SessionHandler(Attachments.Create);
            Routes["/session/:session/attachment/:attachment"]["GET"] = new SessionHandler(Attachments.Get);
            Routes["/session/:session/attachment/:attachment"]["POST"] = new SessionHandler(Attachments.Update);
            Routes["/session/:session/attachment/:attachment"]["DELETE"] = new SessionHandler(Attachments.Delete);

            Routes["/session/:session/clipboard"]["POST"] = new SessionHandler(Clipboards.SetContent);
            Routes["/session/:session/clipboard"]["GET"] = new SessionHandler(Clipboards.GetContent);
            Routes["/session/:session/clipboard"]["DELETE"] = new SessionHandler(Clipboards.Clear);

            Element("/session/:session/element/:target");
            Desktop("/session/:session/desktop");

            if (Configuration.ContainsKey("grid.hub")) {
                Uri uri = new Uri(Configuration["grid.hub"]);
                Dictionary<string, string> hubConfiguration = new Dictionary<string, string>();
                string configPrefix = "grid.configuration.";
                foreach (string key in Configuration.Keys) {
                    if (!key.StartsWith(configPrefix))
                        continue;
                    string shortKey = key.Substring(configPrefix.Length);
                    hubConfiguration[shortKey] = Configuration[key];
                }

                Hub = new GridHub(this, uri, hubConfiguration, Log);
                Hub.Connect();
            }
        }
 internal static SessionHandler GivenThereIsASession(Mock<IWebApiClient> webApiClientMock, Mock<IConfiguration> configurationMock, Action<SessionRegistrationStartedEventArgs> sessionStartedAction, Action<SessionRegistrationCompletedEventArgs> sessionCompletedAction)
 {
     var applicationHelperMock = new Mock<IApplicationInformation>(MockBehavior.Strict);
     applicationHelperMock.Setup(x => x.GetApplicationData()).Returns(() => new ApplicationData());
     var machineHelperMock = new Mock<IMachineInformation>(MockBehavior.Strict);
     machineHelperMock.Setup(x => x.GetMachineData()).Returns(() => new MachineData());
     var userHelperMock = new Mock<IUserInformation>(MockBehavior.Strict);
     userHelperMock.Setup(x => x.GetDataUser()).Returns(() => new UserData());
     var clientMock = new Mock<IQuilt4NetClient>(MockBehavior.Strict);
     clientMock.SetupGet(x => x.Configuration).Returns(() => configurationMock.Object);
     clientMock.SetupGet(x => x.WebApiClient).Returns(() => webApiClientMock.Object);
     clientMock.SetupGet(x => x.Information.Application).Returns(() => applicationHelperMock.Object);
     clientMock.SetupGet(x => x.Information.User).Returns(() => userHelperMock.Object);
     clientMock.SetupGet(x => x.Information.Machine).Returns(() => machineHelperMock.Object);
     var session = new SessionHandler(clientMock.Object);
     session.SessionRegistrationStartedEvent += (semder, e) => { sessionStartedAction?.Invoke(e); };
     session.SessionRegistrationCompletedEvent += (sender, e) => { sessionCompletedAction?.Invoke(e); };
     return session;
 }
Example #4
0
        public async void When_several_threads_are_ending_session_at_the_same_time()
        {
            //Arrange
            var sessionEndCompletedEventCount = 0;
            var sessionEndStartedEventCount = 0;
            var sessionKey = Guid.NewGuid().ToString();
            var webApiClientMock = new Mock<IWebApiClient>(MockBehavior.Strict);
            webApiClientMock.Setup(x => x.CreateAsync<SessionRequest, SessionResponse>(It.IsAny<string>(), It.IsAny<SessionRequest>())).Returns(Task.FromResult(new SessionResponse { SessionKey = sessionKey }));
            webApiClientMock.Setup(x => x.ExecuteCommandAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Guid>())).Returns(Task.FromResult<object>(null)).Callback(() => { System.Threading.Thread.Sleep(500); });
            var configurationMock = new Mock<IConfiguration>(MockBehavior.Strict);
            configurationMock.SetupGet(x => x.Enabled).Returns(true);
            configurationMock.SetupGet(x => x.ProjectApiKey).Returns("ABC123");
            configurationMock.SetupGet(x => x.Session.Environment).Returns((string)null);
            var applicationHelperMock = new Mock<IApplicationInformation>(MockBehavior.Strict);
            applicationHelperMock.Setup(x => x.GetApplicationData()).Returns(new ApplicationData());
            var machineHelperMock = new Mock<IMachineInformation>(MockBehavior.Strict);
            machineHelperMock.Setup(x => x.GetMachineData()).Returns(new MachineData());
            var userHelperMock = new Mock<IUserInformation>(MockBehavior.Strict);
            userHelperMock.Setup(x => x.GetDataUser()).Returns(new UserData());
            var clientMock = new Mock<IQuilt4NetClient>(MockBehavior.Strict);
            clientMock.SetupGet(x => x.Configuration).Returns(() => configurationMock.Object);
            clientMock.SetupGet(x => x.WebApiClient).Returns(() => webApiClientMock.Object);
            clientMock.SetupGet(x => x.Information.Application).Returns(() => applicationHelperMock.Object);
            clientMock.SetupGet(x => x.Information.Machine).Returns(() => machineHelperMock.Object);
            clientMock.SetupGet(x => x.Information.User).Returns(() => userHelperMock.Object);
            var session = new SessionHandler(clientMock.Object);
            session.SessionEndCompletedEvent += delegate { sessionEndCompletedEventCount++; };
            session.SessionEndStartedEvent += delegate { sessionEndStartedEventCount++; };            
            var response = await session.GetSessionKeyAsync();

            //Act
            var task1 = Task.Run(() => session.EndAsync());
            var task2 = Task.Run(() => session.EndAsync());
            var task3 = Task.Run(() => { System.Threading.Thread.Sleep(400); return session.EndAsync(); });
            Task.WaitAll(task1, task2, task3);

            //Assert
            Assert.That(response,Is.EqualTo(sessionKey));
            Assert.That(session.IsRegisteredOnServer, Is.False);
            Assert.That(sessionEndStartedEventCount, Is.EqualTo(1));
            Assert.That(sessionEndCompletedEventCount, Is.EqualTo(1));
            webApiClientMock.Verify(x => x.ExecuteCommandAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Guid>()), Times.Once);
        }
Example #5
0
    /// <summary>
    /// Saves the current profile, existing or newly created.
    /// </summary>
    /// <param name="caller"></param>
    private void SaveCurrentProfile(string caller)
    {
        SecurityController sc   = new SecurityController();
        string             user = sc.GetUserName();

        if (!String.IsNullOrEmpty(this._ptProfileId.Value))
        {
            ProfileId = Int32.Parse(this._ptProfileId.Value);
        }

        if (this._visitTypeStage.Value != "0")
        {
            VisitTypeId = Int32.Parse(this._visitTypeStage.Value);
        }

        PatientEducationDa da = new PatientEducationDa();
        List <string>      checkedPartsList = new List <string>();

        foreach (TreeNode sectionNode in contentTV.Nodes)
        {
            foreach (TreeNode topicNode in sectionNode.ChildNodes)
            {
                foreach (TreeNode subTopicNode in topicNode.ChildNodes)
                {
                    if (subTopicNode.Checked)
                    {
                        checkedPartsList.Add(subTopicNode.Value);
                    }
                }
            }
        }

        if (ProfileId > 0)
        {
            DataTable dbProfilePartsDt = da.GetProfileDocPartsByProfileId(ProfileId);
            // Delete existing profile parts that have been deselected,
            // and update the list of actual new parts to be saved later on.
            foreach (DataRow dr in dbProfilePartsDt.Rows)
            {
                string stId = dr[PatientEdProfileDocPart.SubTopicId].ToString();
                if (!checkedPartsList.Contains(stId))
                {
                    //delete this profile doc part from the db
                    da.DeleteProfileDocPartByProfileIdAndSubTopicId(ProfileId, Int32.Parse(stId));
                }
                else
                {
                    //remove it from the list of checked parts, as we have confirmed it is already in the db
                    checkedPartsList.Remove(stId);
                }
            }

            PatientEdProfile profileBiz = new PatientEdProfile();
            profileBiz.Get(ProfileId);
            profileBiz[PatientEdProfile.UpdatedBy]   = user;
            profileBiz[PatientEdProfile.UpdatedTime] = DateTime.Now.ToString();

            if (caller == "print")
            {
                profileBiz[PatientEdProfile.LastPrintedBy]   = user;
                profileBiz[PatientEdProfile.LastPrintedTime] = DateTime.Now.ToString();
            }
            profileBiz.Save();
        }
        else
        {
            // Saving a brand new profile.
            SessionHandler sh   = new SessionHandler(Session);
            int            ptId = sh.GetPatientId();

            PatientEdProfile profile = new PatientEdProfile();
            profile[PatientEdProfile.PatientId] = ptId.ToString();

            if (this._visitTypeStage.Value != "0")
            {
                profile[PatientEdProfile.ProfileVisitTypeId] = VisitTypeId;
            }
            if (this.ddlDiseaseProfile.SelectedIndex > 0)
            {
                profile[PatientEdProfile.ProfileDiseaseId] = DiseaseId;
            }

            string profileDate = DateTime.Now.ToString();
            profile[PatientEdProfile.ProfileCreateDate] = profileDate;
            profile[PatientEdProfile.EnteredBy]         = user;
            profile[PatientEdProfile.EnteredTime]       = profileDate;
            profile[PatientEdProfile.UpdatedBy]         = user;
            profile[PatientEdProfile.UpdatedTime]       = profileDate;

            if (caller == "print")
            {
                profile[PatientEdProfile.LastPrintedBy]   = user;
                profile[PatientEdProfile.LastPrintedTime] = DateTime.Now.ToString();
            }
            profile.Save();

            ProfileId = Int32.Parse(profile[PatientEdProfile.ProfileId].ToString());
            LoadListOfProfilesTable(ptId);

            ShowProfileLog(true);
        }

        // Add the new profile parts to this profile document
        foreach (string profilePart in checkedPartsList)
        {
            PatientEdProfileDocPart dp = new PatientEdProfileDocPart();
            dp[PatientEdProfileDocPart.ProfileId]  = ProfileId.ToString();
            dp[PatientEdProfileDocPart.SubTopicId] = Int32.Parse(profilePart);
            dp[PatientEdProfileDocPart.ProfileDocPartVersionNumber] = "1.0";
            dp[PatientEdProfileDocPart.ProfileDocPartOrderNumber]   = "1";
            dp.Save();
        }

        LoadExistingProfile();
        GetRootNodes();

        this._callbackType.Value = String.Empty;
    }
Example #6
0
        public void LoginHandler(SessionHandler session)
        {
            try
            {
                var login       = session.CompletedBuffer.GetMessageEntity <LoginPack>();
                var syncContext = new SessionSyncContext()
                {
                    IPv4                 = login.IPV4,
                    MachineName          = login.MachineName,
                    Remark               = login.Remark,
                    CpuInfo              = login.ProcessorInfo,
                    CoreCount            = login.ProcessorCount,
                    MemroySize           = login.MemorySize,
                    StarupDateTime       = login.StartRunTime,
                    Version              = login.ServiceVison,
                    AdminName            = login.UserName,
                    OSVersion            = login.OSVersion,
                    IsCameraExist        = login.ExistCameraDevice,
                    IsRecordExist        = login.ExitsRecordDevice,
                    IsPlayerExist        = login.ExitsPlayerDevice,
                    IsOpenScreenRecord   = login.OpenScreenRecord,
                    IsOpenScreenView     = login.OpenScreenWall,
                    IdentifyId           = login.IdentifyId,
                    RecordScreenIsAction = false,              //桌面记录状态
                    RecordScreenHeight   = login.RecordHeight, //用于桌面记录的高
                    RecordScreenWidth    = login.RecordWidth,  //用于桌面记录宽
                    RecordScreenSpanTime = login.RecordSpanTime,
                    Session              = session
                };

                _syncContexts.Add(syncContext);
                var listItem = new USessionListItem(syncContext);
                syncContext.OnSessionListItem = listItem;
                session.AppTokens[SysConstants.INDEX_WORKER] = syncContext;
                onlineList.Items.Add(listItem);

                //是否开启桌面视图
                if (syncContext.IsOpenScreenView != true)
                {
                    listItem.BackColor = _closeScreenColor;
                }
                else
                {
                    byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.S_MAIN_DESKTOPVIEW, new byte[] { 0 });//强制创建视图
                    session.SendAsync(data);
                }

                //是否桌面记录
                if (syncContext.IsOpenScreenRecord)
                {
                    byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.S_MAIN_SCREEN_RECORD_OPEN,
                                                                  new DesktopRecordGetFramePack()
                    {
                        Height   = syncContext.RecordScreenHeight,
                        Width    = syncContext.RecordScreenWidth,
                        TimeSpan = syncContext.RecordScreenSpanTime
                    });
                    session.SendAsync(data);
                }

                _connect_count++;
                stripConnectedNum.Text = _connect_count.ToString();

                Win32Api.FlashWindow(this.Handle, true); //上线任务栏图标闪烁

                this.WriteRuninglog("计算机:" + syncContext.MachineName + "(" + syncContext.Remark + ") -->已连接控制端!", "ok");
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorByCurrentMethod(ex);
                //可能是旧版本上线包
            }
        }
    private bool DoWork(RunWorkerArgument arg)
    {
        if (GenericHelper.IsUserInteractive())
        {
            if (ConfigHandler.UseTranslation)
            {
                _worker.ReportProgress(-2, Translator.GetText("importingSessions"));
            }
            else
            {
                _worker.ReportProgress(-2, "Importing session(s)...");
            }
        }

        OutputHandler.WriteToLog("Importing session(s)...");

        arg.DatabaseOperation.DisableColumnStoreIndex();
        arg.DatabaseOperation.StopFullTextPopulation();

        bool success = false;

        for (int i = 0; i < arg.ImportSessionInfoList.Count; i++)
        {
            if (GenericHelper.IsUserInteractive())
            {
                _worker.ReportProgress(-1, new ProgressObject(i + 1, arg.ImportSessionInfoList.Count, arg.ImportSessionInfoList[i]));
            }

            List <string> nonDefaultColumns = GetNonDefaultColumns(arg.DatabaseOperation, arg.ImportSessionInfoList[i].SessionId);

            success = SessionHandler.ImportSession(arg.DatabaseOperation, arg.ImportSessionInfoList[i].SessionId, nonDefaultColumns);

            if (!success)
            {
                break;
            }
        }

        if (success)
        {
            OutputHandler.WriteToLog("Importing session(s): Completed");
        }

        if (!ConfigHandler.TempTableCreated)
        {
            if (GenericHelper.IsUserInteractive())
            {
                if (ConfigHandler.UseTranslation)
                {
                    _worker.ReportProgress(-2, Translator.GetText("creatingIndexes"));
                }
                else
                {
                    _worker.ReportProgress(-2, "Creating indexes...");
                }
            }

            OutputHandler.WriteToLog("Creating indexes...");

            arg.DatabaseOperation.CreateIndexes();

            ConfigHandler.TempTableCreated = true;
        }

        if (arg.DatabaseOperation.GetSqlServerVersion() >= 11 && arg.DatabaseOperation.IsColumnStoreSupported())
        {
            if (GenericHelper.IsUserInteractive())
            {
                if (ConfigHandler.UseTranslation)
                {
                    _worker.ReportProgress(-2, Translator.GetText("enableColumnStoreIndex"));
                }
                else
                {
                    _worker.ReportProgress(-2, "Creating Column Store Index...");
                }
            }

            OutputHandler.WriteToLog("Creating Column Store Index...");

            arg.DatabaseOperation.EnableColumnStoreIndex();

            OutputHandler.WriteToLog("Creating Column Store Index: Completed");
        }

        if (GenericHelper.IsUserInteractive())
        {
            if (ConfigHandler.UseTranslation)
            {
                _worker.ReportProgress(-2, Translator.GetText("populatingFullText"));
            }
            else
            {
                _worker.ReportProgress(-2, "Populating full text catalog...");
            }
        }

        OutputHandler.WriteToLog("Populating full text catalog...");

        arg.DatabaseOperation.StartFullTextPopulation();

        return(success);
    }
Example #8
0
 public LoginController(UserService userService,
                        SessionHandler sessionHandler)
 {
     _sessionHandler = sessionHandler;
     _userService    = userService;
 }
Example #9
0
 //耗时操作会导致接收性能严重降低
 public void OnTransmit(SessionHandler session)
 => this._sendTransferredBytes += session.SendTransferredBytes;
 public void OnSessionNotify(SessionHandler session, SessionNotifyType type)
 => OnSessionNotifyPro?.Invoke(session, type);
 /// <summary>
 /// 数据接收事件
 /// </summary>
 /// <param name="session"></param>
 /// <param name="lenght">如果通讯层启用了压缩模式传输,那么length为为解压前的数据大小</param>
 public virtual void OnReceive(SessionHandler session, int lenght)
 {
 }
Example #12
0
// EFormLink;


        override protected void Page_Load(object sender, System.EventArgs e)
        {
            // check if new clinic date was submitted
            if (Request.Form.HasKeys() && Request.Form["clinicDate"] != null)
            {
                currentClinicDate = Request.Form["clinicDate"].ToString();
                Session[SessionKey.CurrentClinicDate] = Request.Form["clinicDate"].ToString();
            }
            else
            {
                SessionHandler sh = new SessionHandler(this.Page.Session);
                currentClinicDate = sh.GetCurrentClinicDate();
            }

            clinicDate.Value = currentClinicDate;



            if (Session[SessionKey.CurrentListCrit] != null && Session[SessionKey.CurrentListCrit].ToString().Length > 0 && Session[SessionKey.CurrentListType] != null && Session[SessionKey.CurrentListType].ToString().Length > 0)
            {
                string listType     = Session[SessionKey.CurrentListType].ToString();
                string listCrit     = Session[SessionKey.CurrentListCrit].ToString();
                string listCritName = "";

                if (Session[SessionKey.CurrentListCritName] != null)
                {
                    listCritName = Session[SessionKey.CurrentListCritName].ToString();
                }


                switch (listType)
                {
                case "Clinic":
                    formSplashCurrentClinic.Text = listCrit + "<br/>on " + currentClinicDate;
                    break;

                case "Protocol":
                    if (!listCritName.Equals(""))
                    {
                        formSplashCurrentClinic.Text = "Patients in<br/>" + listType + " " + listCritName;
                    }
                    else
                    {
                        formSplashCurrentClinic.Text = listType;
                    }
                    clinicDateCal.Visible = false;
                    break;

                case "Physician":
                    if (!listCritName.Equals(""))
                    {
                        formSplashCurrentClinic.Text = "Patients who have visited<br/>" + listCritName;
                    }
                    else
                    {
                        formSplashCurrentClinic.Text = listType;
                    }
                    clinicDateCal.Visible = false;
                    break;

                case "lastname":
                    if (listCrit.Equals("All"))
                    {
                        formSplashCurrentClinic.Text = "All Patients";
                    }
                    else
                    {
                        formSplashCurrentClinic.Text = "Patients with Last Names<br/>Beginning with the Letter \"" + listCrit + "\"";
                    }
                    clinicDateCal.Visible = false;
                    break;

                case "ContactStatus":
                    formSplashCurrentClinic.Text = "Patients on the Following List:<br/>Contact Status -  " + listCrit;
                    clinicDateCal.Visible        = false;
                    break;

                case "ItemsMissing":
                    formSplashCurrentClinic.Text = "Patients with Missing Items";
                    clinicDateCal.Visible        = false;
                    break;

                case "ItemsPending":
                    formSplashCurrentClinic.Text = "Patients with Pending Items";
                    clinicDateCal.Visible        = false;
                    break;

                default:
                    formSplashCurrentClinic.Text = "Patients on the Following List:<br/>" + listType + " -  " + listCrit;
                    clinicDateCal.Visible        = false;
                    break;
                }
            }
            else
            {
                clinicDateCal.Visible = false;
                batchPrintLink.HRef   = "javascript:;";
                batchPrintLink.Attributes["onclick"] = "top.window.location='../PatientLists/PatientListPage.aspx';";
                printForms.Src    = "../../Images/PrintFormsForAListOfPatients.gif";
                printForms.Width  = 88;
                printForms.Height = 75;
            }


            if (Session[SessionKey.PatientId] == null || Session[SessionKey.PatientId].ToString() == "")
            {
                //				currentPatientLink.HRef = "javascript:top.noPatientInSessionRedirect();";
                //				currentPatientLink.Attributes.Add("onclick", "top.noPatientInSessionRedirect();");
                printFormForCurrentPatient.Attributes.Add("onclick", "top.noPatientInSessionRedirect();");
                printFormForCurrentPatient.Attributes.Add("style", "cursor:hand;");
                currentPatientLink.HRef = "";

                //EFormLink.Attributes["onclick"] = "top.noPatientInSessionRedirect();";
            }
            //else
            //{
            //	EFormLink.Attributes["onclick"] = "top.location='../Eforms/Index.aspx?eform=" + Server.UrlEncode("Prostate Surgery EForm") + "';";
            //}



            clinicDateCal.Attributes.Add("onClick", "showCal(this, dataForm." + clinicDate.ClientID.ToString() + ");");
        }
Example #13
0
        private static Command CreateCloseCommand()
        {
            var command = new Command("close", "Close Nauta session");

            command.Handler = CommandHandler.Create(
                async() =>
            {
                Log.Information("Closing Nauta session...");

                Dictionary <string, string> sessionData = null;
                try
                {
                    var sessionContent = await File.ReadAllTextAsync("session.json");
                    sessionData        = JsonSerializer.Deserialize <Dictionary <string, string> >(sessionContent);
                }
                catch (Exception e)
                {
                    Log.Error(e, "Error deserializing session data.");
                }

                if (sessionData != null)
                {
                    // TODO: Improve this
                    var policy = Policy.Handle <HttpRequestException>().WaitAndRetryForeverAsync(
                        retryAttempt => TimeSpan.FromSeconds(5),
                        (exception, retry, timeSpan) =>
                    {
                        Log.Error(exception, "Error closing Nauta session.");
                    });

                    DateTime startDateTime = default;
                    var isTimeAvailable    = sessionData.TryGetValue(SessionDataKeys.Started, out var started) &&
                                             DateTime.TryParse(started, out startDateTime);

                    var sessionHandler = new SessionHandler();

                    // var remainingTime = await policy.ExecuteAsync(() => sessionHandler.RemainingTimeAsync(sessionData));

                    await policy.ExecuteAsync(() => sessionHandler.CloseAsync(sessionData));
                    var endDateTime = DateTime.Now;

                    try
                    {
                        File.Delete("session.json");
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Error deleting persisted session");
                    }

                    //Log.Information(
                    //    "Remaining Time: '{RemainingTime}'.",
                    //    $"{(int)remainingTime.TotalHours}hrs {remainingTime:mm}mn {remainingTime:ss}sec");

                    if (isTimeAvailable)
                    {
                        var elapsedTime = endDateTime.Subtract(startDateTime);
                        Log.Information("Nauta session closed. Duration: '{Duration}'.", $"{(int)elapsedTime.TotalHours}hrs {elapsedTime:mm}mn {elapsedTime:ss}sec");
                    }
                    else
                    {
                        Log.Information("Nauta session closed.");
                    }
                }
                else
                {
                    Log.Information("This command requires an open session. Open a nauta session first with open command.");
                }
            });

            return(command);
        }
Example #14
0
        private static int AuthDataHandler(SessionTcpClient client, byte[] data, int Length)
        {
            ByteRef response    = new ByteRef(33);
            int     MaxUserName = 16;
            int     MaxPassword = 16;
            int     MaxMac      = 24;

            int Success = 1;

            byte Action = data[32];

            // Check if IP banned
            if (!IsIPBanned(client.Session.Ip_address))
            {
                byte[] bUsername = new byte[MaxUserName];
                byte[] bPassword = new byte[MaxPassword];
                byte[] bMac      = new byte[MaxMac];

                Array.Copy(data, 0, bUsername, 0, MaxUserName);
                Array.Copy(data, MaxUserName, bPassword, 0, MaxPassword);
                Array.Copy(data, 0xC0, bMac, 0, MaxMac);

                string Username = Utility.ReadCString(bUsername);
                string Password = Utility.ReadCString(bPassword);
                string Mac      = Utility.ReadCString(bMac);

                client.Session.Mac_address = Mac;

                // Check for valid string input
                if (!Utility.ValidAuthString(Username, MaxUserName) || !Utility.ValidAuthString(Password, MaxPassword))
                {
                    //bad characters in username or password
                    Logger.Warning("Invalid characters sent from: {0}", new object[] { client.Session.Ip_address });
                    response.Resize(1);
                    response.Set <byte>(0, LOGINRESULT.ERROR);
                    Success = 0;
                }
                else
                {
                    Username = Username.Trim();
                    Password = Password.Trim();

                    // TODO: check to see if account locked out

                    if (Action == (byte)LOGINRESULT.ATTEMPT)
                    {
                        Account acc = DBClient.GetOne <Account>(DBREQUESTTYPE.ACCOUNT, a => a.Username.Equals(Username));

                        if (acc != null && acc.Password.Equals(Utility.GenMD5(Password)))
                        {
                            uint AccountID = acc.AccountId;

                            // TODO: handle maintenance mode and gm accounts
                            if (ConfigHandler.MaintConfig.MaintMode > 0) // && !MySQL.IsGMAccount(AccountID))
                            {
                                response.Fill(0, 0x00, 33);
                                Success = 0;
                            }
                            else if (acc.Status.HasFlag(ACCOUNTSTATUS.NORMAL))
                            {
                                if (SessionHandler.AlreadyLoggedIn(AccountID))
                                {
                                    Success = 0;

                                    // TODO: might want to see about killing the other logged in session, but we'll see if it's necessary
                                }
                                else
                                {
                                    // TODO: reset accounts last modification date
                                    //MySQL.ResetAccountLastModify(AccountID);

                                    client.Session.Account_id   = AccountID;
                                    client.Session.Session_hash = Utility.GenerateSessionHash(AccountID, Username);
                                    response.Set <byte>(0, LOGINRESULT.SUCCESS);
                                    response.Set <uint>(1, client.Session.Account_id);
                                    response.BlockCopy(client.Session.Session_hash, 5, 16);
                                    client.Session.Status = SESSIONSTATUS.ACCEPTINGTERMS;
                                    Success = 1;
                                }
                            }
                            else if (acc.Status.HasFlag(ACCOUNTSTATUS.BANNED))
                            {
                                response.Fill(0, 0x00, 33);
                                Success = 0;
                            }
                        }
                        else
                        {
                            //if (acc != null && acc.Locked)
                            //{
                            //  TODO: increment attempts in accounts table
                            //uint newLockTime = 0;
                            //if (attempts + 1 >= 20) newLockTime = 172800; // 48 hours
                            //else if (attempts + 1 == 10) newLockTime = 3600; // 1 hour
                            //else if (attempts + 1 == 5) newLockTime = 900; // 15 minutes
                            //fmtQuery = "UPDATE accounts SET attempts = %u, lock_time = UNIX_TIMESTAMP(NOW()) + %u WHERE id = %d;";
                            //if (Sql_Query(SqlHandle, fmtQuery, attempts + 1, newLockTime, accountId) == SQL_ERROR)
                            //    ShowError("Failed to update lock time for account: %s\n", name.c_str());
                            //}
                            Logger.Warning("Invalid login attempt for: {0}", new object[] { Username });
                            response.Resize(1);
                            response.Set <byte>(0, LOGINRESULT.ERROR);
                            Success = 0;
                        }
                    }
                    else if (Action == (byte)LOGINRESULT.CREATE)
                    {
                        response.Resize(1);
                        if (ConfigHandler.MaintConfig.MaintMode == 0)
                        {
                            Account acc           = DBClient.GetOne <Account>(DBREQUESTTYPE.ACCOUNT, a => a.Username.Equals(Username));
                            bool    accountexists = (acc != null);

                            uint maxAccountID = DBClient.GetMaxID(DBREQUESTTYPE.ACCOUNT);

                            if (!accountexists && maxAccountID > 0)
                            {
                                uint AccountID = maxAccountID + 1;

                                Account newAccount = new Account()
                                {
                                    AccountId      = maxAccountID + 1,
                                    Username       = Username,
                                    Password       = Utility.GenMD5(Password),
                                    TimeCreate     = Utility.Timestamp(),
                                    TimeLastModify = Utility.Timestamp(),
                                    // TODO: make these configurable
                                    ContentIds = 3,
                                    Expansions = 14,
                                    Features   = 13,
                                    Status     = ACCOUNTSTATUS.NORMAL
                                };

                                bool success = DBClient.InsertOne <Account>(DBREQUESTTYPE.ACCOUNT, newAccount);

                                if (success)
                                {
                                    response.Set <byte>(0, LOGINRESULT.ERROR_CREATE);
                                    Success = 0;
                                }
                                else
                                {
                                    response.Set <byte>(0, LOGINRESULT.SUCCESS_CREATE);
                                    Success = 1;
                                }
                            }
                            else
                            {
                                response.Set <byte>(0, LOGINRESULT.ERROR_CREATE);
                                Success = 0;
                            }
                        }
                        else
                        {
                            response.Set <byte>(0, LOGINRESULT.ERROR);
                            Success = 0;
                        }
                    }
                }
            }
            else
            {
                response.Set <byte>(0, LOGINRESULT.ERROR_CREATE);
                Success = 0;
            }
            if (Success >= 0)
            {
                client.Session.AuthSend(response.Get());
                if (Success == 0)
                {
                    SessionHandler.KillSession(client.Session);
                }
            }
            return(Success);
        }
 public virtual void SessionClosed(SessionHandler session)
 {
     this.Text = Adapter.TipText;
 }
 public virtual void ContinueTask(SessionHandler session)
 {
 }
Example #17
0
		/// <summary>
		/// Creates a new HTTPSession
		/// </summary>
		/// <param name="Local">Source IPEndPoint to use</param>
		/// <param name="Remote">Remote IPEndPoint to connect to</param>
		/// <param name="CreateCallback">Succussful callback</param>
		/// <param name="CreateFailedCallback">Failed callback</param>
		/// <param name="State">StateObject</param>
		public HTTPSession(IPEndPoint Local, IPEndPoint Remote, SessionHandler CreateCallback, SessionHandler CreateFailedCallback, Object State)
		{
			OpenSource.Utilities.InstanceTracker.Add(this);
			local_ep = Local;
			
			OnCreateSession += CreateCallback;
			OnCreateFailed += CreateFailedCallback;

			StateObject = State;

			MainSocket = new AsyncSocket(4096);
			MainSocket.Attach(Local,ProtocolType.Tcp);
			MainSocket.OnConnect += new AsyncSocket.ConnectHandler(HandleConnect);
			MainSocket.OnConnectFailed += new AsyncSocket.ConnectHandler(HandleConnectFailed);
			MainSocket.OnDisconnect += new AsyncSocket.ConnectHandler(HandleDisconnect);
			MainSocket.OnSendReady += new AsyncSocket.OnSendReadyHandler(HandleReady);

			MainSocket.Connect(Remote);
		}
Example #18
0
 protected override void OnError(SocketError error)
 {
     SessionHandler.OnStateChanged(Id, ServerNetSessionState.Error);
 }
 public void DeviceNotExisthandler(SessionHandler session)
 {
     this.ShowTip("视频打开失败,未检测到视频设备!");
 }
 public virtual void OnMessage(SessionHandler session, MessageHead head)
 {
 }
Example #21
0
 protected override void OnDisconnected()
 {
     SessionHandler.OnStateChanged(Id, ServerNetSessionState.Disconnected);
 }
Example #22
0
        readonly int pre_alloc_count = 2;               // read, write

        public CNetworkService()
        {
            this.connected_count          = 0;
            this.session_created_callback = null;
        }
Example #23
0
        private void UserLogin()
        {
            try
            {
                button_login.Enabled = false;
                //ProgressBar.Start();
                //ProgressBar.Show();
                var settingObject = System.Configuration.ConfigurationSettings.AppSettings;
                var company       = settingObject["Company"];

                var auth = new RefUserAuth.IauthClient().login(txtUserName.Text.Trim(), txtPassword.Text.Trim(),
                                                               int.Parse(company), "DuoSoftPhone");

                var sip = ProfileManagementHandler.GetSipProfile(auth.SecurityToken, auth.guUserId);
                if (sip == null)
                {
                    button_login.Enabled = true;
                    //ProgressBar.Stop();
                    //ProgressBar.Hide();
                    txtPassword.Text = string.Empty;
                    Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Fail to Get SIP Profile", Logger.LogLevel.Error);
                    MessageBox.Show("Fail to Get SIP Profile", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var id       = Guid.NewGuid().ToString();
                var callBack = new SoftPhoneResourceHandler(auth.SecurityToken, auth.TenantID, auth.CompanyID);
                var ip       = GetLocalIpAddress();

                callBack.OnResourceRegistrationCompleted += (r) =>
                {
                    #region Resource Registration

                    this.Invoke(new MethodInvoker(delegate
                    {
                        button_login.Enabled = true;
                        //ProgressBar.Stop();
                        //ProgressBar.Hide();
                        var passWord     = txtPassword.Text;
                        txtPassword.Text = string.Empty;

                        switch (r.Command)
                        {
                        case WorkflowResultCode.ACDS101:     //- Agent sucessfully registered (ACDS101)
                            Hide();
                            new FormDialPad(auth, id, sip, ip, passWord).ShowDialog(this);
                            this.Close();
                            Environment.Exit(0);
                            break;

                        case WorkflowResultCode.ACDE101:     //- Agent already registered with different IP (ACDE101)
                            Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Agent already registered with different IP-ARDS Code : ACDE101", Logger.LogLevel.Info);
                            MessageBox.Show("Agent already registered with different IP", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);

                            break;

                        default:
                            Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Login Fail-- ARDS not allow to Login. ARDS Code : " + r.Command, Logger.LogLevel.Info);
                            MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);

                            break;
                        }
                    }));

                    #endregion Resource Registration
                };

                callBack.ResourceRegistration(auth, ip);
            }
            catch (Exception exception)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    button_login.Enabled = true;
                    //ProgressBar.Stop();
                    //ProgressBar.Hide();
                    txtPassword.Text = string.Empty;
                }));
                var id = SessionHandler.UniqueId(txtUserName.Text);
                Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, String.Format("Login fail. {0}", id), exception, Logger.LogLevel.Error);
                MessageBox.Show(@"Login Fail", @"Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #24
0
 public SessionHandlerTest()
 {
     _repository = new SessionsRepositoryFake();
     _handler    = new SessionHandler(_repository);
 }
Example #25
0
 public TalentDetailPage(MajaTalent talent, SessionHandler sessionHandler)
 {
     InitializeComponent();
     BindingContext = ViewModel = new TalentDetailViewModel(talent, sessionHandler);
     TalentActiveLabel.SizeChanged += TalentActiveLabel_SizeChanged;
 }
Example #26
0
        // TODO: MIGRATION - DELETE ME
        /// <summary>
        /// Main method for ensuring Patient in Session matches the Patient represented in the current Page.
        /// Places Patient (as specified by Patient Biz) in Session (if needed), Log's Patient View (if needed) and updates header via client script.
        /// </summary>
        /// <param name="page">The current Page which contains relevant Session</param>
        /// <param name="ptBiz">The Patient BusinessObject representing the current Patient</param>
        public void PutPatientInSession(Page page, Patient ptBiz)
        {
            int patientId = (int)ptBiz[Patient.PatientId];

            // Get Current Session
            HttpSessionState _session = page.Session;

            // Load SessionHandler for setting/reseting SESSION varaibles
            SessionHandler sHandler = new SessionHandler(_session);

            // LOG PATIENT VIEW AND SET PATIENT IN SESSION (if needed)
            // If no patient in session or patient is session != current, then log view and update session
            if (!sHandler.VerifyPatientInSession(ptBiz))
            {
                // get encrypted patient id
                string encPatientId = Security.CustomCryptoHelper.Encrypt(patientId.ToString());

                // log that user is viewing Patient
                UserController uController = new UserController(_session);
                uController.ViewPatient(patientId);

                // update Patient in Session
                sHandler.UpdateSessionPatientInfo(ptBiz);

                // SET PATIENT IN HEADER (UI) - generate client script for syncing header info
                // Check if patient is Deceased
                string isDeceased = this.IsPatientDeceased(ptBiz).ToString().ToLower();

                // HANDLE SPECIAL CASE for identifiers (default to mrn)
                string         identifierField = string.Empty;// _session[SessionKey.PtMRN].ToString();
                UserController uc = new UserController(page.Session);
                if (uc.HasDefaultIdentifierType())
                {
                    string idType = uc.GetDefaultIdentifierType();
                    if (!string.IsNullOrEmpty(idType))
                    {
                        identifierField = GetPatientIdentifier(patientId, idType);
                    }
                    else
                    {
                        identifierField = GetPatientMRN(ptBiz);
                    }
                }
                else
                {
                    identifierField = GetPatientMRN(ptBiz);
                }

                // build a list of client arguments, with single quotes escaped
                string[] clientScriptArgumentsList = new string[]
                {
                    GetPatientFirstName(ptBiz),
                    GetPatientLastName(ptBiz),
                    identifierField,
                    GetPatientDateOfBirth(ptBiz),
                    encPatientId
                };
                for (int i = 0; i < clientScriptArgumentsList.Length; i++)
                {
                    string identifier = clientScriptArgumentsList[i];
                    clientScriptArgumentsList[i] = PageUtil.EscapeSingleQuotes(identifier);
                }
                // generates 'a','b','c','d'
                string clientScriptArguments = "'" + string.Join("','", clientScriptArgumentsList) + "'";
                // function which sets patient header
                string clientScriptName = "top.changePatientInHeader";
                // full client script,i.e., if(f) { f(a,b,c..); }
                string fullClientScript = "if(" + clientScriptName + ") { " + clientScriptName + "(" + clientScriptArguments + "," + isDeceased + "); }";
                page.ClientScript.RegisterStartupScript(page.GetType(), "RegsiterPatientInSession", fullClientScript, true);
            }
        }
Example #27
0
 public void OnReceive(SessionHandler session)
 => this._receiveTransferredBytes += session.ReceiveTransferredBytes;
Example #28
0
        public IActionResult Get()
        {
            var obj = new SessionHandler(this);

            return(obj.GetSession());
        }
Example #29
0
        protected void signinClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string user_name = userName.Text.Trim();
                    string pass_word = password.Text.Trim();

                    LoginResponse login = MyUser.validateUserIS(user_name, pass_word);

                    if (login.credentials == Constants.VALID && login.success == true)
                    {
                        using (DataTable dt = new BL_User().selectByUserName(new Model.ML_User()
                        {
                            username = user_name
                        }))
                        {
                            string type    = dt.Rows[0]["role_name"].ToString();
                            string userID  = dt.Rows[0]["id_user"].ToString();
                            string loginID = login.loginID;

                            SessionHandler.initiateLoginSession(user_name, type, login.token, userID, loginID);

                            switch (type.Trim())
                            {
                            case Constants.AIGROW_ADMIN:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_ADMIN + "Index.aspx", false);
                                break;

                            case Constants.CHG_NETWORK:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_NETWORK_OWNER + "Index.aspx", false);
                                break;

                            case Constants.AIGROW_CUSTOMER:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_CUSTOMER + "Index.aspx", false);
                                break;

                            case Constants.CHG_OWNER:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_CHARGE_POINT_OWNER + "Index.aspx", false);
                                break;

                            case Constants.CHG_STAFF:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_STAFF + "Index.aspx", false);
                                break;

                            case Constants.CHG_ACCOUNTANT:
                                Response.Redirect(Constants.HOME_PATH_DASHBOARDS_ACCOUNTANT + "Index.aspx", false);
                                break;

                            default:
                                Response.Redirect(string.Format("{0}?error={1}&token={2}", Constants.LOGIN_URL, Messages.undefinedError, Encryption.createSHA1(Messages.undefinedError)), false);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (login.errorCode == Constants.EC_UserNotActive)
                        {
                            string message = login.errorMessage + " " + Messages.activateYourAccount + " " + Messages.resendActivationEmail.Replace("<here>", "<a href=\"../ResendActivationEmail.aspx?username="******"\">here</a>");

                            string message_enc = WebUtility.UrlEncode(Encryption.Base64Encode(message));
                            Response.Redirect(string.Format("{0}?message_enc={1}&token={2}", Constants.LOGIN_URL, message_enc, Encryption.createSHA1(message_enc)), false);
                        }
                        else
                        {
                            Response.Redirect(string.Format("{0}?error={1}&token={2}", Constants.LOGIN_URL, Messages.invalidUsernameOrPassword, Encryption.createSHA1(Messages.invalidUsernameOrPassword)), false);
                        }
                    }
                }
                catch (Exception error)
                {
                    ApplicationUtilities.writeMsg(error.StackTrace);
                    ApplicationUtilities.writeMsg(error.Message);

                    Response.Redirect(string.Format("{0}?error={1}&token={2}", Constants.LOGIN_URL, Messages.undefinedError, Encryption.createSHA1(Messages.undefinedError)), false);
                }
            }
            else
            {
                userName.Focus();
            }
        }
 public PlayableCharacterController(DungeonsAndDragonsContext context, SessionHandler sessionHandler, IHubContext <DnDHub> hubcontext)
 {
     _context        = context;
     _sessionHandler = sessionHandler;
     _hubcontext     = hubcontext;
 }
Example #31
0
 public LoginPage(SessionHandler sessionHandler)
 {
     InitializeComponent();
     BindingContext = ViewModel = new LoginPageViewModel(sessionHandler);
 }
 public HomeController(ILogger <HomeController> logger, SessionHandler sessionHandler)
 {
     _logger         = logger;
     _sessionHandler = sessionHandler;
 }
Example #33
0
        public async void When_registering_session_and_quilt4net_is_disabled()
        {
            //Arrange
            var sessionRegistrationStartedEventCount = 0;
            var sessionRegistrationCompletedEventCount = 0;
            var webApiClientMock = new Mock<IWebApiClient>(MockBehavior.Strict);
            var configurationMock = new Mock<IConfiguration>(MockBehavior.Strict);
            configurationMock.SetupGet(x => x.Enabled).Returns(false);
            configurationMock.SetupGet(x => x.ProjectApiKey).Returns("ABC123");
            configurationMock.SetupGet(x => x.AllowMultipleInstances).Returns(true);
            var clientMock = new Mock<IQuilt4NetClient>(MockBehavior.Strict);
            clientMock.SetupGet(x => x.Configuration).Returns(configurationMock.Object);
            var session = new SessionHandler(clientMock.Object);
            session.SessionRegistrationStartedEvent += delegate { sessionRegistrationStartedEventCount++; };
            session.SessionRegistrationCompletedEvent += delegate { sessionRegistrationCompletedEventCount++; };

            //Act
            var response = await session.GetSessionKeyAsync();

            //Assert
            Assert.That(response, Is.Null);
            Assert.That(sessionRegistrationStartedEventCount, Is.EqualTo(0));
            Assert.That(sessionRegistrationCompletedEventCount, Is.EqualTo(0));
            webApiClientMock.Verify(x => x.CreateAsync<SessionRequest, SessionResponse>(It.IsAny<string>(), It.IsAny<SessionRequest>()), Times.Never);
        }
Example #34
0
        public void GetSessionReturnsSharedSession()
        {
            var _session = new SessionHandler().GetCurrentSession();

            Assert.AreSame(Session, _session);
        }
Example #35
0
        private void TestHelper(IObjectFactory factory, SessionHandler handler)
        {
            MockRepository mocks = new MockRepository();

            ISession session = mocks.StrictMock<ISession>();
            JsBridge bridge = new JsBridge(session, factory);
            HostedMode.Host = bridge;
            SessionHelper helper = new SessionHelper(bridge, session);
            using (mocks.Ordered()) {
                handler(helper);
            }
            mocks.ReplayAll();

            bridge.DispatchForever();

            mocks.VerifyAll();
        }
Example #36
0
 private SessionHandler <IAppSession, IPackageInfo> CreateNewPackageReceivedHandler(SessionHandler <IAppSession, WebSocketPackageInfo> externalHandler)
 {
     return((s, p) => externalHandler(s, (WebSocketPackageInfo)p));
 }
 private SessionHandler<IAppSession, IPackageInfo> CreateNewPackageReceivedHandler(SessionHandler<IAppSession, WebSocketPackageInfo> externalHandler)
 {
     return (s, p) => externalHandler(s, (WebSocketPackageInfo)p);
 }
 public PictureHandler(SessionHandler sessionHandler)
 {
     this.sessionHandler = sessionHandler ?? throw new NullReferenceException();
 }
 static SessionHandler_Fields()
 {
     NULL = new NULLSessionHandler();
 }
Example #40
0
		public SessionResponder(SessionHandler handler) : base(null) {
			this.handler = handler;
		}