Пример #1
0
		public void TestNoArgs()
		{
			SessionData s = Classes.CLI.ParseCLIArguments(new string[]{});
			SessionData result = new SessionData();
			Assert.AreEqual(result.GetType(), s.GetType());
			
		}
Пример #2
0
        private void OnPropertyChanged(SessionData Session, String AttributeName)
        {
            if (Session == null)
                return;

            sessionDetailPropertyGrid.Refresh();
        }
Пример #3
0
        private void loadCalendar()
        {
            Home frmchild = new Home();
            SessionData sesh;
            string filepath;
            calRef = new List<CalendarRef>();
            DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\Jack\Documents\GitHub\CycleAnalysis\CycleDataReader\Data");
            FileInfo[] Files = dinfo.GetFiles("*.txt");

            foreach (FileInfo file in Files)
            {
                filepath = file.Directory + "\\" + file.ToString();

                frmchild = new Home();
                frmchild.LoadingFile(filepath);
                sesh = new SessionData();
                sesh = frmchild.getSession();

                // Makes a calendar ref for later
                CalendarRef calendar = new CalendarRef(sesh, filepath);
                calRef.Add(calendar);

                monthCalendar1.AddBoldedDate(sesh.getDateTime());
            }

            for (int i = 0; i < calRef.Count; i++)
            {
                Console.WriteLine(calRef[i].getSession().getDateTime().Date);
            }
        }
Пример #4
0
        public ISessionFactory GetSessionFactory(long orderId)
        {
            lock (_orderSessionsDict)
            {
                ISessionFactory sessionFactory = null;

                if (_orderSessionsDict.ContainsKey(orderId))
                {
                    var sessiondata = _orderSessionsDict[orderId];

                    sessiondata.LastUsed = DateTime.Now;

                    sessionFactory = sessiondata.SessionFactory;
                }

                if (sessionFactory == null)
                {
                    sessionFactory = BuildSessionFactory(orderId);

                    _orderSessionsDict[orderId] = new SessionData
                    {
                        LastUsed = DateTime.Now,
                        SessionFactory = sessionFactory
                    };
                }

                var sessionFactoriesToDelete = _orderSessionsDict.Where(x => x.Value.LastUsed < DateTime.Now.AddHours(-1)).Select(x => x.Key).ToList();

                sessionFactoriesToDelete.ForEach(x => _orderSessionsDict.Remove(x));

                return sessionFactory;
            }
        }
Пример #5
0
        private Simulator()
        {
            _drivers = new DriverContainerCollection();
            _sessionData = new SessionData();

            Connection.Instance.SessionInfoUpdated += SdkOnSessionInfoUpdated;
            Connection.Instance.TelemetryUpdated += SdkOnTelemetryUpdated;
        }
Пример #6
0
    public static SessionData GetInstance()
    {
        if (m_instance == null)
        {
            m_instance = new SessionData();
        }

        return m_instance;
    }
 private static IDictionary<string, string> GenerateLoginRequest(SessionData sessionData, string user, string pass)
     => new Dictionary<string, string>
     {
         { "lt", sessionData.Lt },
         { "execution", sessionData.Execution },
         { "_eventId", "submit" },
         { "username", user },
         { "password", pass }
     };
Пример #8
0
        public void it_skips_a_two_zero_frame()
        {
            var s = new SessionData { SessionInfo = new SessionData._SessionInfo { Sessions = new[] { new SessionData._SessionInfo._Sessions() } } };

            var inputSamples = CreateSamplesFromFrameNumbers(s, 1, 2, 3, 0, 0, 4, 5);

            var samples = iRacingSDK.DataSampleExtensions.VerifyReplayFrames(inputSamples).ToList();

            Assert.That(FrameNumbersFromSamples(samples), Is.EqualTo(new[] { 1, 2, 3, 4, 5 }));
        }
Пример #9
0
        public void it_skips_if_no_matching_session()
        {
            var s = new SessionData { SessionInfo = new SessionData._SessionInfo { Sessions = new[] { new SessionData._SessionInfo._Sessions() } } };

            var inputSamples = CreateSamplesFromFrameNumbers(s, 1, 2, 3, 4, 5);

            inputSamples.First().Telemetry["SessionNum"] = 1;
               
            var samples = iRacingSDK.DataSampleExtensions.VerifyReplayFrames(inputSamples).ToList();

            Assert.That(FrameNumbersFromSamples(samples), Is.EqualTo(new [] { 2, 3, 4, 5 }));
        }
        private static async Task<string> GetLoginTicket(string username, string password, System.Net.Http.HttpClient tempHttpClient, SessionData sessionData)
        {
            HttpResponseMessage loginResp;
            var loginRequest = GenerateLoginRequest(sessionData, username, password);
            using (var formUrlEncodedContent = new FormUrlEncodedContent(loginRequest))
            {
                loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl, formUrlEncodedContent).ConfigureAwait(false);
            }

            var ticketId = ExtracktTicketFromResponse(loginResp);
            return ticketId;
        }
Пример #11
0
 private void SelectedSessionChanged(SessionData Session)
 {
     SessionData OldSession = sessionDetailPropertyGrid.SelectedObject as SessionData;
     if (OldSession != null)
     {
         OldSession.OnPropertyChanged -= OnPropertyChanged;
     }
     sessionDetailPropertyGrid.SelectedObject = Session;
     if (Session != null)
     {
         Session.OnPropertyChanged += OnPropertyChanged;
     }
 }
Пример #12
0
        public RemoteFileListPanel(PscpTransfer transfer, DockPanel dockPanel, SessionData session)
        {
            Log.InfoFormat("Started new File Transfer Session for {0}", session.SessionName);
            m_Session = session;
            m_DockPanel = dockPanel;
            m_Transfer = transfer;
            m_MouseFollower = new dlgMouseFeedback();
            InitializeComponent();
            
            this.TabText = session.SessionName;

            LoadDirectory(m_Path);
        }
Пример #13
0
        public ctlPuttyPanel(SessionData session, PuttyClosedCallback callback)
        {
            m_Session = session;
            m_ApplicationExit = callback;
            m_puttyStartInfo = new PuttyStartInfo(session);

            InitializeComponent();

            this.Text = session.SessionName;
            this.TabText = session.SessionName;
            this.TextOverride = session.SessionName;

            CreatePanel();
            AdjustMenu();
        }
Пример #14
0
        public Session(
			SessionManagerHandler sessionManagerHandler, 
			FileHandlerFactoryLocator fileHandlerFactoryLocator,
			PersistedObject<Dictionary<ID<ISession, Guid>, SessionData>> persistedSessionDatas,
			ID<ISession, Guid> sessionId,
			SessionData sessionData)
        {
            this.sessionManagerHandler = sessionManagerHandler;
            this.fileHandlerFactoryLocator = fileHandlerFactoryLocator;
            this.persistedSessionDatas = persistedSessionDatas;
            this.sessionId = sessionId;

            this.maxAge = sessionData.maxAge;
            this.lastQuery = sessionData.lastQuery;
            this.keepAlive = sessionData.keepAlive;
        }
Пример #15
0
 /// <summary>
 /// Add a model system to the project
 /// </summary>
 /// <param name="modelSystem">The model system to add to the project</param>
 /// <param name="error">An error message in case of failure</param>
 /// <returns>True if the model system was added successfully</returns>
 public bool AddModelSystem(ModelSystem modelSystem, ref string error)
 {
     if(modelSystem == null)
     {
         throw new ArgumentNullException("modelSystem");
     }
     lock (EditingSessionsLock)
     {
         if(!this.Project.AddModelSystem(modelSystem, ref error))
         {
             return false;
         }
         var temp = new SessionData[EditingSessions.Length + 1];
         Array.Copy(EditingSessions, temp, EditingSessions.Length);
         EditingSessions = temp;
         return true;
     }
 }
Пример #16
0
 public SampleSessionDataSource()
 {
     Session = new SessionData
     {
         Title = "The Awesomeness Factor: Taking your Greatness to 11",
         //Image = new BitmapImage(new Uri("http://qedcode.com/extras/Perry_Headshot_Medium.jpg", UriKind.Absolute)),
         Day = "Sat",
         Time = "2:30",
         Room = "Room: Vestibule on the Square",
         Track = "Architecture",
         Description = "When you are this awesome, it can't get any better, right?\n\nWrong!\n\nYou can always get more awesome! We'll show you how. You can multiply your greatness by the awesome factor. This will make you even more awesome than you already are. We'll give you three actionable recommendations for cranking up your greatness to 11.\n\nGo team awesome!",
         Speaker = "Michael L Perry",
         SpeakerBio = "Software is math. Michael L Perry has built upon the works of mathematicians like Bertrand Meyer, James Rumbaugh, and Donald Knuth to develop a mathematical system for software development. He has captured this system in a set of open source projects, Update Controls and Correspondence. As a Principal Consultant at Improving Enterprises, he applies mathematical concepts to building scalable and robust enterprise systems. You can find out more at qedcode.com.",
         AddVisible = Visibility.Visible,
         RemoveVisible = Visibility.Collapsed
         //StatusBrush = Application.Current.Resources["UnscheduledStatusBrush"] as Brush
     };
 }
Пример #17
0
        DataSample[] CreateSamplesFromFrameNumbers(SessionData s, params int[] frameNumbers)
        {
            DataSample lastSample = null;

            return frameNumbers.Select(n =>
                {
                    var sample = new DataSample
                    {
                        IsConnected = true,
                        Telemetry = new Telemetry
                        {
                            { "SessionNum", 0 },
                            { "ReplayFrameNum", n }
                        },
                        LastSample = lastSample
                    };

                    sample.Telemetry.SessionData = s;
                    lastSample = sample;
                    return sample;
                }
            ).ToArray();
        }
        static DataSample[] CreatesSamplesForDistancesOf(params float[] distances)
        {
            var laps = distances.Select(d => (int)d).ToArray();
            var distPcts = distances.Select(d => d - (float)(int)d).ToArray();

            var s = new SessionData { DriverInfo = new SessionData._DriverInfo { Drivers = new[] { new SessionData._DriverInfo._Drivers { UserName = "******", CarNumberRaw = 1 } } } };

            var result = new List<DataSample>();

            for (int i = 0; i < laps.Length; i++)
                result.Add(new DataSample
                {
                    IsConnected = true,
                    SessionData = s,
                    Telemetry = new Telemetry {	
                        { "CarIdxLap",	new[] { laps[i] }	}, 
                        { "CarIdxLapDistPct", new[] { distPcts[i] } },
                        { "CarIdxTrackSurface", new[] { TrackLocation.OnTrack } },
                        { "ReplayFrameNum", 10 + i }
                    }
                });

            return result.ToArray();
        }
Пример #19
0
    public void buyCharacter(int character)
    {
        Dictionary <int, bool> skins = SessionData.getSkins();
        int coins = SessionData.getCoins();
        int price;

        switch (character)
        {
        case 1:
            price = 2;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField1.SetActive(false);
            }
            break;

        case 2:
            price = 3;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField2.SetActive(false);
            }
            break;

        case 3:
            price = 3;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField3.SetActive(false);
            }
            break;

        case 4:
            price = 2;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField4.SetActive(false);
            }
            break;

        case 5:
            price = 4;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField5.SetActive(false);
            }
            break;

        case 6:
            price = 7;
            if (price <= coins)
            {
                coins = coins - price;
                SessionData.setCoins(coins);
                skins[character] = !skins[character];
                SessionData.setSkins(skins);
                buyField6.SetActive(false);
            }
            break;
        }

        SessionData.saveSessionFile();
    }
Пример #20
0
 static void ApplyIconForWindow(ToolWindow win, SessionData session)
 {
     win.Icon = GetIconForSession(session);
 }
 public Trial(SessionData data, XmlElement n)
 {
     ParseGameSpecificVars(n, data);
 }
Пример #22
0
    public void RequestRoomData(RoomKey roomKey, GameEvent.OnEventCompleteDelegate onComplete)
    {
        if (!IsRoomDataRequestPending)
        {
            // Cached room data is available
            if (SessionData.GetInstance().CurrentGameData.HasRoomData(roomKey))
            {
                // Update which room we're currently in
                SessionData.GetInstance().CurrentGameData.CurrentRoomKey = roomKey;

                // Notify the controller
                Debug.Log("Using cached room data");
                m_gameWorldController.OnRoomLoaded(roomKey);

                // Notify the caller
                if (onComplete != null)
                {
                    onComplete();
                }
            }
            // Have to request room data from the server
            else
            {
                AsyncJSONRequest            roomDataRequest = AsyncJSONRequest.Create(m_gameWorldController.gameObject);
                Dictionary <string, object> request         = new Dictionary <string, object>();

                request["game_id"] = SessionData.GetInstance().GameID;
                request["room_x"]  = roomKey.x;
                request["room_y"]  = roomKey.y;
                request["room_z"]  = roomKey.z;

                IsRoomDataRequestPending = true;

                roomDataRequest.POST(
                    ServerConstants.roomDataRequestURL,
                    request,
                    (AsyncJSONRequest asyncRequest) =>
                {
                    if (asyncRequest.GetRequestState() == AsyncJSONRequest.eRequestState.succeded)
                    {
                        JsonData response     = asyncRequest.GetResult();
                        string responseResult = (string)response["result"];

                        if (responseResult == "Success")
                        {
                            SessionData sessionData = SessionData.GetInstance();
                            GameData currentGame    = sessionData.CurrentGameData;
                            RoomData roomData       = RoomData.FromObject(response);

                            // Add the room data to the room cache
                            currentGame.SetCachedRoomData(roomData.RoomKey, roomData);

                            // Update which room we're currently in
                            currentGame.CurrentRoomKey = roomKey;

                            // Notify the controller
                            Debug.Log("Room Loaded");
                            m_gameWorldController.OnRoomLoaded(roomData.RoomKey);
                        }
                        else
                        {
                            Debug.Log("Room Data Request Failed: " + responseResult);
                            m_gameWorldController.OnRequestFailed(responseResult);
                        }
                    }
                    else
                    {
                        Debug.Log("Room Data Request Failed: " + asyncRequest.GetFailureReason());
                        m_gameWorldController.OnRequestFailed("Connection Failed!");
                    }

                    // Notify the caller
                    if (onComplete != null)
                    {
                        onComplete();
                    }

                    IsRoomDataRequestPending = false;
                });
            }
        }
    }
Пример #23
0
 protected override HElement GetElement(SessionData sessionData) => _response;
 public SessionDataPacket(SessionData sessionData)
 {
     SessionData = sessionData;
 }
Пример #25
0
 public override void _Process(float delta)
 {
     SessionData.Update();
 }
Пример #26
0
    void StartSession(int node, int roomId)
    {
        string str = "ReceiveStartSessionRequest[roomId:" + roomId + "]";

        Debug.Log(str);

        SessionData response = new SessionData();

        RoomContent room = null;

        if (rooms_.ContainsKey(roomId) == true)
        {
            room = rooms_[roomId];

            response.endPoints = new EndPointData[maxMemberNum];

            int index = 0;
            for (int i = 0; i < maxMemberNum; ++i)
            {
                if (room.members[i] != -1)
                {
                    IPEndPoint ep = network_.GetEndPoint(room.members[i]) as IPEndPoint;
                    response.endPoints[index].ipAddress = ep.Address.ToString();
                    response.endPoints[index].port      = NetConfig.GAME_PORT;
                    ++index;
                }
            }

            response.members = index;
            response.result  = MatchingResult.Success;
        }
        else
        {
            response.result = MatchingResult.RoomIsGone;
        }

        if (room != null)
        {
            rooms_[roomId].isClosed = true;

            str = "Request room id: " + roomId + " MemberNum:" + response.members + " result:" + response.result;
            Debug.Log(str);

            for (int i = 0; i < response.members; ++i)
            {
                str = "member[" + i + "]" + ":" + response.endPoints[i].ipAddress + ":" + response.endPoints[i].port;
                Debug.Log(str);
            }

            int index = 0;
            for (int i = 0; i < room.members.Length; ++i)
            {
                int target = room.members[i];

                if (target != -1)
                {
                    response.playerId = index;

                    SessionPacket packet = new SessionPacket(response);

                    network_.SendReliable <SessionData>(target, packet);

                    ++index;
                }
            }
        }
    }
Пример #27
0
        private async void TimerCommandExecute()
        {
            if (String.IsNullOrEmpty(StudentCode))
            {
                await Application.Current.MainPage.DisplayAlert("Atención", "Debe rellenar el código de alumno", "Aceptar");

                return;
            }

            if (!IsAllConnectedDevices(lDevices))
            {
                await Application.Current.MainPage.DisplayAlert("Atención", "Hay dispositivos que no están conectados. Por favor, pulse el botón reconnectar", "Aceptar");

                return;
            }

            sessionInit             = new SessionInit();
            sessionInit.SessionId   = session.ID;
            sessionInit.StudentCode = StudentCode;
            sessionInit.Date        = DateTime.Now;


            StudentCode = StudentCode;
            if (StartStop.Equals(INICIAR) || StartStop.Equals(REANUDAR))
            {
                StudentCodeEntry = false;
                StartStop        = DETENER;
            }
            else
            {
                StudentCodeEntry = true;
                StartStop        = INICIAR;
            }

            WriteDevices("1");

            Device.StartTimer(TimeSpan.FromMilliseconds(10), () =>
            {
                if (StartStop.Equals(INICIAR) || StartStop.Equals(REANUDAR))
                {
                    WriteDevices("0");
                    return(false);
                }
                else
                {
                    intMilliseconds += 10;

                    if (intMilliseconds == 1000)
                    {
                        intMilliseconds = 0;
                        intSeconds++;
                    }

                    if (intSeconds == 60)
                    {
                        intSeconds = 0;
                        intMinutes++;
                    }

                    if (intMinutes / 10 == 0)
                    {
                        Minutes = "0" + intMinutes.ToString();
                    }
                    else
                    {
                        Minutes = intMinutes.ToString();
                    }

                    if (intSeconds / 10 == 0)
                    {
                        Seconds = "0" + intSeconds.ToString();
                    }
                    else
                    {
                        Seconds = intSeconds.ToString();
                    }

                    if (intMilliseconds / 100 == 0)
                    {
                        Milliseconds = "0" + (intMilliseconds / 10).ToString();
                    }
                    else
                    {
                        Milliseconds = (intMilliseconds / 10).ToString();
                    }

                    return(true);
                }
            });

            if (StartStop.Equals(INICIAR))
            {
                StartStop = REANUDAR;
                var action = await Application.Current.MainPage.DisplayActionSheet("¿Que desea hacer?", PAUSAR, FINALIZAR);

                if (action.Equals(FINALIZAR))
                {
                    sessionInit.Time = Minutes + ":" + Seconds + ":" + Milliseconds;
                    ResetChronometer();
                    Debug.WriteLine("Guardando datos.....");
                    App.Database.SaveSessionInit(sessionInit);

                    foreach (DeviceData deviceData in lDeviceData)
                    {
                        SessionData sessionData = new SessionData();
                        sessionData.SessionInitId = sessionInit.ID;
                        sessionData.DeviceName    = deviceData.DeviceName;
                        sessionData.Data          = deviceData.Data;
                        App.Database.SaveSessionData(sessionData);
                    }
                }
            }
        }
Пример #28
0
 private void SetupSessionRepositoryMock(string token, SessionData sessionData)
 => sessionRepositoryMock
 .Setup(repository => repository.GetByTokenAsync(token))
 .ReturnsAsync(sessionData);
Пример #29
0
        public void ExerciseProfileData_RemoveMaxWeightDay_ChangeMaxWeightInRecords()
        {
            var         profile = (ProfileDTO)profiles[0].Tag;
            SessionData data    = CreateNewSession(profile, ClientInformation);

            var exercise = CreateExercise(Session, null, "test", "t", ExerciseType.Nogi, MechanicsType.Isolation,
                                          ExerciseForceType.Pull);

            var day = new TrainingDay(DateTime.Now.Date.AddDays(-1));

            day.Profile = profiles[0];

            var entry = new StrengthTrainingEntry();

            entry.MyPlace = GetDefaultMyPlace(profiles[0]);
            day.AddEntry(entry);
            var item = new StrengthTrainingItem();

            item.Exercise = exercise;
            entry.AddEntry(item);
            var serie1 = new Serie("10x10");

            item.AddSerie(serie1);
            var serie2 = new Serie("7x40");

            item.AddSerie(serie2);
            var serie3 = new Serie("4x20");

            item.AddSerie(serie3);
            insertToDatabase(day);

            var day1 = new TrainingDay(DateTime.Now.Date);

            day1.Profile = profiles[0];

            entry         = new StrengthTrainingEntry();
            entry.MyPlace = GetDefaultMyPlace(profiles[0]);
            day1.AddEntry(entry);
            item          = new StrengthTrainingItem();
            item.Exercise = exercise;
            entry.AddEntry(item);
            var serie11 = new Serie("10x5");

            item.AddSerie(serie11);
            var serie12 = new Serie("1x50");

            item.AddSerie(serie12);
            var serie13 = new Serie("4x11");

            item.AddSerie(serie13);
            insertToDatabase(day1);

            ExerciseProfileData exData = new ExerciseProfileData();

            exData.Exercise     = exercise;
            exData.Profile      = profiles[0];
            exData.Serie        = serie12;
            exData.MaxWeight    = 50;
            exData.Repetitions  = 1;
            exData.TrainingDate = day1.TrainingDate;
            insertToDatabase(exData);

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                DeleteTrainingDayParam param = new DeleteTrainingDayParam();
                param.TrainingDayId          = day1.GlobalId;
                Service.DeleteTrainingDay(data.Token, param);
            });

            exData = Session.QueryOver <ExerciseProfileData>().SingleOrDefault();
            Assert.AreEqual(profiles[0], exData.Profile);
            Assert.AreEqual(exercise, exData.Exercise);
            Assert.AreEqual(40m, exData.MaxWeight);
            Assert.AreEqual(7, exData.Repetitions);
            Assert.AreEqual(DateTime.Now.Date.AddDays(-1), exData.TrainingDate);
            Assert.AreEqual(serie2.GlobalId, exData.Serie.GlobalId);
        }
Пример #30
0
 public override bool ContainsSession(string key)
 {
     return(SessionData.ContainsKey(key));
 }
Пример #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // This comes from the Admin User (protected)
        try
        {
            string id       = Request["id"];
            IMyLog logItemX = MyLog.GetLogger("ItemX");

            switch (id)
            {
            case "GetAllTelNumbers":     // as used by the fone
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);

                Response.ContentType = "text/plain";
                Response.Write("GetAllTelNumbers:\r\n");
                Response.Write(DateTime.UtcNow.ToString() + "\r\n");
                {
                    int telCounter  = 0;
                    int userCounter = 0;
                    List <MobileNoHandlerWithUserName> commercialUsersToConfirm = new List <MobileNoHandlerWithUserName>();

                    DSSwitch.appUser().RetrieveAll(
                        Data_AppUserFile.SortType.Date,
                        delegate(Data_AppUserFile d)
                    {
                        if ((d.AccountStatus == Data_AppUserFile.eUserStatus.verified_welcome_No_sent) ||
                            (d.AccountStatus == Data_AppUserFile.eUserStatus.verified_welcome_queued) ||
                            (d.AccountStatus == Data_AppUserFile.eUserStatus.verified_checkingTelNumbers))
                        {
                            userCounter++;
                            Response.Write("User: "******"\r\n");
                            foreach (string m1 in d.MobileNumbers_AllConfirmed__.MobileNumberArray)
                            {
                                telCounter++;
                                Response.Write(m1 + "\r\n");
                            }
                            foreach (string m1 in d.MobileNumbers_AllUnConfirmed__.MobileNumberArray)
                            {
                                telCounter++;
                                Response.Write(m1 + "\r\n");
                            }
                        }
                        else if (
                            (d.AccountStatus == Data_AppUserFile.eUserStatus.commercial_monthly) ||
                            (d.AccountStatus == Data_AppUserFile.eUserStatus.commercial_payassent))
                        {
                            if (d.AddNumber_ActivateOnSyncRequest)
                            {
                                userCounter++;
                                Response.Write("User: "******"\r\n");
                                MobileNoHandlerWithUserName conf = new MobileNoHandlerWithUserName(d.Email);
                                foreach (string tel1 in d.MobileNumbers_AllUnConfirmed__.MobileNumberArray)
                                {
                                    telCounter++;
                                    Response.Write(tel1 + "\r\n");
                                    conf.Handler.Add(tel1);
                                }
                                commercialUsersToConfirm.Add(conf);
                            }
                        }
                    },
                        logItemX);
                    Response.Write("Sumary: Active user: "******" Tel: " + telCounter.ToString() + "\r\n");
                }
                break;

            case "GetTelNumbersBlockedUsers":
                Response.ContentType = "text/plain";
                Response.Write("GetTelNumbersBlockedUsers:\r\n");
                Response.Write(DateTime.UtcNow.ToString() + "\r\n");
                {
                    int telCounter  = 0;
                    int userCounter = 0;

                    DSSwitch.appUser().RetrieveAll(
                        Data_AppUserFile.SortType.Date,
                        delegate(Data_AppUserFile d)
                    {
                        if (d.AccountStatus == Data_AppUserFile.eUserStatus.blocked)
                        {
                            userCounter++;
                            Response.Write("User: "******"\r\n");
                            foreach (string m1 in d.MobileNumberArray())
                            {
                                telCounter++;
                                Response.Write(m1 + "\r\n");
                            }
                        }
                    },
                        logItemX);
                    Response.Write("Sumary: Active user: "******" Tel: " + telCounter.ToString());
                }
                break;

            case "GetTelNumbers":
                // no check as this comes from the TrayApp - NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                Response.ContentType = "text/plain";
                Response.Write("GetTelNumbers:\r\n");
                Response.Write(DateTime.UtcNow.ToString() + "\r\n");
                {
                    int telCounter  = 0;
                    int userCounter = 0;

                    DSSwitch.appUser().RetrieveAll(
                        Data_AppUserFile.SortType.Date,
                        delegate(Data_AppUserFile d)
                    {
                        if (d.IsAccountActive("Welcome"))
                        {
                            userCounter++;
                            Response.Write("User: "******"\r\n");
                            foreach (string m1 in d.MobileNumberArray())
                            {
                                telCounter++;
                                Response.Write(m1 + "\r\n");
                            }
                        }
                    },
                        logItemX);
                    Response.Write("Sumary: Active user: "******" Tel: " + telCounter.ToString());
                }
                break;

            case "Home":
                Response.Redirect("~/");
                break;

            case "LibVer":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);

                Assembly a = Assembly.GetAssembly(typeof(IMyLog));
                Response.ContentType = "text/plain";
                a.WriteAssemblyVersion(Response.Output);
                break;

            case "DSSwitch":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                Response.ContentType = "text/plain";
                Response.Write("appUser:   "******"\r\n");
                Response.Write("appWallet: " + DSSwitch.appWallet().GetInfo() + "\r\n");
                Response.Write("msgFile00: " + DSSwitch.msgFile00().GetInfo(NiceASP.SessionData.SessionsSystem_Get(Session)) + "\r\n");
                Response.Write("msgFile02: " + DSSwitch.msgFile02().GetInfo(NiceASP.SessionData.SessionsSystem_Get(Session)) + "\r\n");
                Response.Write("msgFile04: " + DSSwitch.msgFile04().GetInfo(NiceASP.SessionData.SessionsSystem_Get(Session)) + "\r\n");
                Response.Write(DSSwitch.GetMaintenanceLog() + "\r\n");
                break;

            case "SetSubSystem":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                string val = Request["val"];
                var    sub = DSSwitch.full().GetSystems(false).FirstOrDefault(_ => _.Name == val);
                if (sub == null)
                {
                    Response.ContentType = "text/plain";
                    Response.Write("No such SubSystem " + val + "\r\n");
                }
                else
                {
                    SessionData.SessionsSystem_Set(Session, sub);
                    Response.Redirect("~/Admin.aspx");
                }
                break;

            case "ShowSubSystem":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                Response.ContentType = "text/plain";
                DSSwitch.full().GetSystems(false).ForEach(_ => Response.Write(string.Format("{0}, {1}, {2}\r\n", _.Name, _.APIId, _.Default)));
                Response.Write("\r\n");
                var cur = SessionData.SessionsSystem_Get(Session);
                Response.Write(string.Format("currently on\r\n{0}, {1}, {2}\r\n", cur.Name, cur.APIId, cur.Default));
                break;

            case "Screen":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                Response.ContentType = "image/png";
                byte[] baImg;
                using (DataFile_ScreenShot ss = new DataFile_ScreenShot(NiceASP.SessionData.SessionsSystem_Get(Session), DataFile_Base.OpenType.ReadOnly_CreateIfNotThere))
                {
                    MemoryStream ms = new MemoryStream();
                    ss.imgScreen.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    baImg = ms.ToArray();
                }
                Response.OutputStream.Write(baImg, 0, baImg.Length);
                Response.OutputStream.Flush();
                break;

            case "AllValues":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                Response.ContentType = "text/plain";
                int count = 0;
                foreach (string k1 in Request.ServerVariables)
                {
                    Response.Write(count++.ToString() + ":" + k1 + " = " + Request.ServerVariables[k1] + "\r\n");
                }
                using (StreamReader sr = new StreamReader(Request.InputStream))
                {
                    Response.Write(sr.ReadToEnd());
                    Response.Write("\r\n");
                }
                Response.Write("Done a");
                break;

            case "TestX":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);

                Response.ContentType = "text/plain";
                string pathX = Request.ServerVariables["APPL_PHYSICAL_PATH"];

                Response.Write("in1b: " + pathX + "\n");
                pathX = Directory.GetParent(pathX).FullName;
                foreach (string p1 in Directory.GetFiles(pathX))
                {
                    Response.Write(p1 + "\n");
                }

                Response.Write("in2: " + pathX + "\n");
                pathX = Directory.GetParent(pathX).FullName;
                foreach (string p1 in Directory.GetFiles(pathX))
                {
                    Response.Write(p1 + "\n");
                }

                Response.Write("in3: " + pathX + "\n");
                foreach (string p1 in Directory.GetFiles(pathX))
                {
                    Response.Write(p1 + "\n");
                }

                throw new NotImplementedException("end");

            case "Dir":
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);

                FolderNames.CreateFoldersForAsp(NiceASP.SessionData.SessionsSystem_Get(Session));
                Response.ContentType = "text/plain";
                Response.Write("Done Dir");
                break;

            default:
                NiceASP.SessionData.LoggedOnOrRedirectToRoot(Session, Response, true);
                throw new ArgumentException();
                //break;
            }
        }
        catch (Exception se)
        {
            Response.ContentType = "text/plain";
            Response.Write("ups");
            Response.Write(se.ToString());
            Response.Write(se.Message);
        }
    }
 /// <summary>
 /// Parses Game specific variables for this Trial from the given XmlElement.
 /// If no parsable attributes are found, or fail, then it will generate some from the given GameData.
 /// Used when parsing a Trial that IS defined in the Session file.
 /// </summary>
 public virtual void ParseGameSpecificVars(XmlNode n, SessionData data)
 {
     XMLUtil.ParseAttribute(n, ATTRIBUTE_DELAY, ref delay);
 }
Пример #33
0
 // Update is called once per frame
 void Update()
 {
     userCoins.text = SessionData.getCoins().ToString();
 }
        public IEnumerable <ProductDetailResponse> GetSubCategoryList(string catId)
        {
            catId = System.Net.WebUtility.UrlDecode(catId);

            catId = catId.Replace("+", "%20");
            catId = System.Net.WebUtility.UrlDecode(catId);
            catId = catId.Replace(" ", "+");

            bool ret = default(bool);
            IEnumerable <ProductDetail> categoryData = null;
            int ProductTypeId = 0;
            IList <ProductDetailResponse> responsedata = new List <ProductDetailResponse>();

            try
            {
                if (HttpContext.Current.Session[ApplicationConstant.UserSession] != null)
                {
                    SessionData sessionObject = (SessionData)HttpContext.Current.Session[ApplicationConstant.UserSession];

                    if (string.IsNullOrEmpty(catId))
                    {
                        ProductDetailResponse response = new ProductDetailResponse();
                        response.Status = ResponseStatus.Failed;
                        response.Error  = "Parameter mismatch";
                        responsedata.Add(response);
                    }
                    else
                    {
                        ProductTypeId = Convert.ToInt32(EncryptionHelper.AesDecryption(Convert.ToString(catId), EncryptionKey.LOG));
                        var connectionString = "AggieGlobal";
                        var repo             = new ProductManager(connectionString);
                        categoryData = repo.GetSubCategoryList(ProductTypeId, sessionObject._userId);
                        if (categoryData != null && categoryData.Count() > default(int))
                        {
                            foreach (ProductDetail detail in categoryData)
                            {
                                ProductDetailResponse response = new ProductDetailResponse();
                                response.ProductName          = detail.ProductName.Trim();
                                response.ProductTypeName      = detail.ProductTypeName.Trim();
                                response.ProductImageLocation = detail.ProductImageLocation; //fileurl(detail.ProductName.Trim());
                                response.ProductTypeName      = detail.ProductTypeName.Trim();
                                response.ProductId            = EncryptionHelper.AesEncryption(Convert.ToString(detail.ProductId), EncryptionKey.LOG);
                                response.catImageName         = detail.catImageName;
                                response.prodImageName        = detail.prodImageName;
                                response.Status = ResponseStatus.Successful;
                                if (detail.CategoryID == ProductType.Crop.GetHashCode())
                                {
                                    response.prodType = ProductType.Crop;
                                }
                                else if (detail.CategoryID == ProductType.LiveStock.GetHashCode())
                                {
                                    response.prodType = ProductType.LiveStock;
                                }
                                else if (detail.CategoryID == ProductType.Resource.GetHashCode())
                                {
                                    response.prodType = ProductType.Resource;
                                }
                                responsedata.Add(response);
                            }
                        }
                        else
                        {
                            ProductDetailResponse response = new ProductDetailResponse();
                            response.Error  = "Failed to retreive data";
                            response.Status = ResponseStatus.Failed;
                            responsedata.Add(response);
                        }
                        repo.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                ProductDetailResponse response = new ProductDetailResponse();
                response.Status = ResponseStatus.Failed;
                response.Error  = "Failed to retreive data";
                responsedata.Add(response);
                AggieGlobalLogManager.Fatal("ProductController :: GetCategoryList failed :: " + ex.Message);
            }
            return(responsedata);
        }
Пример #35
0
        public void InitializePage(string functionName, string pageKey, string itemKey, SessionData session)
        {
            this.FunctionName = functionName;
            this.KeyOfPage    = pageKey;
            this.itemKey      = itemKey;
            this.sessionData  = session;


            this.InitializePage();
        }
        public CommonModuleResponse CreateSubCategory([FromBody] CommonModuleResponse file)
        {
            string relativePath = string.Empty;

            var myFile = System.Web.Hosting.HostingEnvironment.MapPath("~/ModuleImg/" + relativePath);

            if (file != null && file.fileStream != null && file.fileStream.Length > default(int) && file.productdata != null)
            {
                try
                {
                    if (HttpContext.Current.Session[ApplicationConstant.UserSession] != null)
                    {
                        try
                        {
                            string imageName = Guid.NewGuid() + ".png";
                            relativePath = file.productdata.ProductImageLocation + imageName;

                            var connectionString = "AggieGlobal";
                            var repo             = new ProductManager(connectionString);
                            if (HttpContext.Current.Session[ApplicationConstant.UserSession] != null)
                            {
                                SessionData   sessionObject = (SessionData)HttpContext.Current.Session[ApplicationConstant.UserSession];
                                ProductDetail detailData    = new ProductDetail();
                                detailData.ProductName          = file.productdata.ProductName.Trim();
                                detailData.ProductTypeName      = file.productdata.ProductTypeName.Trim();
                                detailData.ProductImageLocation = imageName;
                                detailData.ProductTypeName      = file.productdata.ProductTypeName.Trim();
                                detailData.CategoryID           = Convert.ToInt32(EncryptionHelper.AesDecryption(file.productdata.CategoryID, EncryptionKey.LOG));
                                detailData.UserId    = sessionObject._userId;
                                detailData.Status    = ResponseStatus.Successful;
                                detailData.ProductId = repo.CreateSubCategory(detailData);
                                if (detailData.ProductId > default(int))
                                {
                                    myFile += relativePath;
                                    File.WriteAllBytes(myFile, file.fileStream);

                                    file                       = new CommonModuleResponse();
                                    file.productdata           = new ProductDetailResponse();
                                    file.productdata.ProductId = System.Net.WebUtility.UrlEncode(Convert.ToString(EncryptionHelper.AesEncryption(detailData.ProductId.ToString(), EncryptionKey.LOG)));
                                    file.productdata.Status    = ResponseStatus.Successful;
                                }
                                else
                                {
                                    file        = new CommonModuleResponse();
                                    file.Error  = "Failed to save product";
                                    file.Status = ResponseStatus.Failed;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            file        = new CommonModuleResponse();
                            file.Status = ResponseStatus.Failed;
                            file.Error  = "Unable to save product file";
                            AggieGlobalLogManager.Fatal("CommonController :: UploadFile failed :: " + ex.Message);
                        }
                    }
                }
                catch (Exception e)
                {
                    file        = new CommonModuleResponse();
                    file.Status = ResponseStatus.Failed;
                    file.Error  = "Unable to save product file";
                    AggieGlobalLogManager.Fatal("CommonController :: UploadFile failed :: " + e.Message);
                }
            }
            return(file);
        }
Пример #37
0
        override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
        {
            SqlConnectionString   opt    = (SqlConnectionString)options;
            SqlConnectionPoolKey  key    = (SqlConnectionPoolKey)poolKey;
            SqlInternalConnection result = null;
            SessionData           recoverySessionData = null;
            SqlConnection         sqlOwningConnection = owningConnection as SqlConnection;
            bool applyTransientFaultHandling          = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false;

            SqlConnectionString userOpt = null;

            if (userOptions != null)
            {
                userOpt = (SqlConnectionString)userOptions;
            }
            else if (sqlOwningConnection != null)
            {
                userOpt = (SqlConnectionString)(sqlOwningConnection.UserConnectionOptions);
            }

            if (sqlOwningConnection != null)
            {
                recoverySessionData = sqlOwningConnection._recoverySessionData;
            }

            if (opt.ContextConnection)
            {
                result = GetContextConnection(opt, poolGroupProviderInfo);
            }
            else
            {
                bool redirectedUserInstance       = false;
                DbConnectionPoolIdentity identity = null;

                // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
                // Used by notifications.
                if (opt.IntegratedSecurity || opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
                {
                    if (pool != null)
                    {
                        identity = pool.Identity;
                    }
                    else
                    {
                        identity = DbConnectionPoolIdentity.GetCurrent();
                    }
                }

                // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
                // If "user instance=true" is in the connection string, we're using SSE user instances
                if (opt.UserInstance)
                {
                    // opt.DataSource is used to create the SSE connection
                    redirectedUserInstance = true;
                    string instanceName;

                    if ((null == pool) ||
                        (null != pool && pool.Count <= 0))     // Non-pooled or pooled and no connections in the pool.

                    {
                        SqlInternalConnectionTds sseConnection = null;
                        try {
                            // What about a failure - throw?  YES!
                            //



                            SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */, false /* set Enlist = false */);
                            sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false, applyTransientFaultHandling: applyTransientFaultHandling);
                            // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
                            instanceName = sseConnection.InstanceName;

                            if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal))
                            {
                                throw SQL.NonLocalSSEInstance();
                            }

                            if (null != pool)   // Pooled connection - cache result
                            {
                                SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                                // No lock since we are already in creation mutex
                                providerInfo.InstanceName = instanceName;
                            }
                        }
                        finally {
                            if (null != sseConnection)
                            {
                                sseConnection.Dispose();
                            }
                        }
                    }
                    else   // Cached info from pool.
                    {
                        SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                        // No lock since we are already in creation mutex
                        instanceName = providerInfo.InstanceName;
                    }

                    // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
                    //       retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
                    // options immutable - stored in global hash - don't modify
                    opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */, null /* do not modify the Enlist value */);
                    poolGroupProviderInfo = null; // null so we do not pass to constructor below...
                }
                result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData, pool, key.AccessToken, applyTransientFaultHandling: applyTransientFaultHandling);
            }
            return(result);
        }
Пример #38
0
        public void Test()
        {
            var      cycleDef = createCycle();
            DateTime date     = new DateTime(2012, 03, 26);//monday
            var      cycle    = new SupplementsCycleDTO();

            cycle.Name         = "Sterydy";
            cycle.Weight       = 85;
            cycle.TrainingDays = string.Format("{0}C,{1}C,{2}C", (int)DayOfWeek.Monday, (int)DayOfWeek.Wednesday, (int)DayOfWeek.Friday);
            cycle.StartDate    = date;
            cycle.SupplementsCycleDefinitionId = cycleDef.GlobalId;
            var         profile1 = (ProfileDTO)profiles[0].Tag;
            SessionData data     = CreateNewSession(profile1, ClientInformation);

            MyTrainingDTO result = null;

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                MyTrainingOperationParam param = new MyTrainingOperationParam();
                param.Operation = MyTrainingOperationType.Start;

                param.MyTraining = cycle;
                result           = service.MyTrainingOperation(data.Token, param);
            });
            var dbCycle = Session.Get <SupplementCycle>(result.GlobalId);

            Assert.AreEqual(28, dbCycle.EntryObjects.Count);
            //Assert.AreEqual(SuplementsEntryDTO.EntryTypeId, dbCycle.TypeId);
            var entries = dbCycle.EntryObjects.OrderBy(x => x.TrainingDay.TrainingDate).Cast <SuplementsEntry>().ToList();

            foreach (var entry in entries)
            {
                Assert.IsNotNull(entry.LoginData);
                Assert.IsNull(entry.Reminder);

                if (entry.TrainingDay.TrainingDate.DayOfWeek == DayOfWeek.Monday ||
                    entry.TrainingDay.TrainingDate.DayOfWeek == DayOfWeek.Wednesday ||
                    entry.TrainingDay.TrainingDate.DayOfWeek == DayOfWeek.Friday)
                {
                    Assert.AreEqual(8.5, entry.Items.ElementAt(0).Dosage);
                    Assert.AreEqual(Model.DosageType.Grams, entry.Items.ElementAt(0).DosageType);
                    Assert.AreEqual(bcaa.GlobalId, entry.Items.ElementAt(0).Suplement.GlobalId);
                    Assert.AreEqual(Model.TimeType.OnEmptyStomach, entry.Items.ElementAt(0).Time.TimeType);

                    Assert.AreEqual(8.5, entry.Items.ElementAt(1).Dosage);
                    Assert.AreEqual(Model.DosageType.Grams, entry.Items.ElementAt(1).DosageType);
                    Assert.AreEqual(bcaa.GlobalId, entry.Items.ElementAt(1).Suplement.GlobalId);
                    Assert.AreEqual(Model.TimeType.BeforeWorkout, entry.Items.ElementAt(1).Time.TimeType);

                    Assert.AreEqual(8.5, entry.Items.ElementAt(2).Dosage);
                    Assert.AreEqual(Model.DosageType.Grams, entry.Items.ElementAt(2).DosageType);
                    Assert.AreEqual(bcaa.GlobalId, entry.Items.ElementAt(2).Suplement.GlobalId);
                    Assert.AreEqual(Model.TimeType.AfterWorkout, entry.Items.ElementAt(2).Time.TimeType);
                }
                else
                {
                    Assert.AreEqual(8.5, entry.Items.ElementAt(0).Dosage);
                    Assert.AreEqual(Model.DosageType.Grams, entry.Items.ElementAt(0).DosageType);
                    Assert.AreEqual(bcaa.GlobalId, entry.Items.ElementAt(0).Suplement.GlobalId);
                    Assert.AreEqual(Model.TimeType.OnEmptyStomach, entry.Items.ElementAt(0).Time.TimeType);
                }
            }
        }
Пример #39
0
        internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
        {
            Task runningReconnect = _currentReconnectionTask;

            // This loop in the end will return not completed reconnect task or null
            while (runningReconnect != null && runningReconnect.IsCompleted)
            {
                // clean current reconnect task (if it is the same one we checked
                Interlocked.CompareExchange <Task>(ref _currentReconnectionTask, null, runningReconnect);
                // make sure nobody started new task (if which case we did not clean it)
                runningReconnect = _currentReconnectionTask;
            }
            if (runningReconnect == null)
            {
                if (_connectRetryCount > 0)
                {
                    SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
                    if (tdsConn._sessionRecoveryAcknowledged)
                    {
                        TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
                        if (!stateObj.ValidateSNIConnection())
                        {
                            if (tdsConn.Parser._sessionPool != null)
                            {
                                if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
                                {
                                    // >1 MARS session
                                    if (beforeDisconnect != null)
                                    {
                                        beforeDisconnect();
                                    }
                                    OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
                                }
                            }
                            SessionData cData = tdsConn.CurrentSessionData;
                            cData.AssertUnrecoverableStateCountIsCorrect();
                            if (cData._unrecoverableStatesCount == 0)
                            {
                                bool callDisconnect = false;
                                lock (_reconnectLock)
                                {
                                    runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
                                    if (runningReconnect == null)
                                    {
                                        if (cData._unrecoverableStatesCount == 0)
                                        { // could change since the first check, but now is stable since connection is know to be broken
                                            _originalConnectionId = ClientConnectionId;
                                            _recoverySessionData  = cData;
                                            if (beforeDisconnect != null)
                                            {
                                                beforeDisconnect();
                                            }
                                            try
                                            {
                                                _supressStateChangeForReconnection = true;
                                                tdsConn.DoomThisConnection();
                                            }
                                            catch (SqlException)
                                            {
                                            }
                                            runningReconnect = Task.Run(() => ReconnectAsync(timeout));
                                            // if current reconnect is not null, somebody already started reconnection task - some kind of race condition
                                            Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
                                            _currentReconnectionTask = runningReconnect;
                                        }
                                    }
                                    else
                                    {
                                        callDisconnect = true;
                                    }
                                }
                                if (callDisconnect && beforeDisconnect != null)
                                {
                                    beforeDisconnect();
                                }
                            }
                            else
                            {
                                if (beforeDisconnect != null)
                                {
                                    beforeDisconnect();
                                }
                                OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
                            }
                        } // ValidateSNIConnection
                    }     // sessionRecoverySupported
                }         // connectRetryCount>0
            }
            else
            { // runningReconnect = null
                if (beforeDisconnect != null)
                {
                    beforeDisconnect();
                }
            }
            return(runningReconnect);
        }
Пример #40
0
	void StartSession(int node, int roomId)
	{
		string str = "ReceiveStartSessionRequest[roomId:" + roomId + "]";
		Debug.Log(str);
		
		SessionData response = new SessionData();

		RoomContent room = null;
		if (rooms_.ContainsKey(roomId) == true) {
			
			room = rooms_[roomId];

			response.endPoints = new EndPointData[maxMemberNum];
			
			int index = 0;
			for (int i = 0; i < maxMemberNum; ++i) {
				if (room.members[i] != -1) {
					
					IPEndPoint ep = network_.GetEndPoint(room.members[i]) as IPEndPoint;
					response.endPoints[index].ipAddress = ep.Address.ToString();
					response.endPoints[index].port = NetConfig.GAME_PORT;
					++index;
				}	
			}
			
			response.members = index;
			response.result = MatchingResult.Success;
		}
		else {
			response.result = MatchingResult.RoomIsGone;
		}

		if (room != null) {

			rooms_[roomId].isClosed = true;

			str = "Request room id: " + roomId + " MemberNum:" + response.members + " result:" + response.result;
			Debug.Log(str);

			for (int i = 0; i < response.members; ++i) {
				str = "member[" + i + "]" + ":" + response.endPoints[i].ipAddress + ":" + response.endPoints[i].port;
				Debug.Log(str);
			}

			int index = 0;
			for (int i = 0; i < room.members.Length; ++i) {

				int target = room.members[i];

				if (target != -1) {
						
					response.playerId = index;

					SessionPacket packet = new SessionPacket(response);
					
					network_.SendReliable<SessionData>(target, packet);

					++index;
				}
			}


		}
	}
Пример #41
0
    public void RequestDrainEnergyTank(Point3d entryPoint, EnergyTankData energyTankData)
    {
        Debug.Log("GameWorldModel:requestDrainEnergyTank - Draining energy tank id="
                  + energyTankData.energy_tank_id + " at position (" + entryPoint.x + ", " + entryPoint.y + ")");

        if (!IsDrainEnergyTankRequestPending)
        {
            GameData                    gameData = SessionData.GetInstance().CurrentGameData;
            CharacterEntity             entity   = GetCharacterEntity(CurrentCharacterID);
            AsyncDrainEnergyTankRequest drainEnergyTankRequest = null;

            IsDrainEnergyTankRequestPending = true;

            drainEnergyTankRequest =
                new AsyncDrainEnergyTankRequest(m_gameWorldController.gameObject, entity, entryPoint, energyTankData);
            drainEnergyTankRequest.Execute(
                (AsyncDrainEnergyTankRequest asyncRequest) =>
            {
                IsDrainEnergyTankRequestPending = false;

                switch (asyncRequest.ResultCode)
                {
                case AsyncDrainEnergyTankRequest.eResult.success:
                    {
                        Debug.Log("GameWorldModel:requestDrainEnergyTank - Drain Succeeded!");

                        // Tell anyone listening on IRC that the game state changed
                        m_gameWorldController.SendCharacterUpdatedGameEvent();

                        // Parse any incoming game events
                        if (asyncRequest.ServerResponse != null)
                        {
                            gameData.ParseEventResponse(asyncRequest.ServerResponse);
                        }

                        // If there were new events, notify the controller so that
                        // it can start playing the events back
                        if (!gameData.IsEventCursorAtLastEvent)
                        {
                            m_gameWorldController.OnGameHasNewEvents();
                        }
                    }
                    break;

                case AsyncDrainEnergyTankRequest.eResult.failed_path:
                case AsyncDrainEnergyTankRequest.eResult.failed_server_denied:
                    {
                        Debug.LogError("GameWorldModel:requestDrainEnergyTank - " + asyncRequest.ResultDetails);

                        m_gameWorldController.OnCharacterActionDisallowed(asyncRequest);
                    }
                    break;

                case AsyncDrainEnergyTankRequest.eResult.failed_server_connection:
                    {
                        Debug.LogError("GameWorldModel:requestDrainEnergyTank - " + asyncRequest.ResultDetails);

                        m_gameWorldController.OnRequestFailed("Connection Failed!");
                    }
                    break;
                }
            });
        }
    }
Пример #42
0
 /// <summary>
 /// Removes a model system from the project
 /// </summary>
 /// <param name="index">The index to remove</param>
 /// <param name="error">An error message in case of failure</param>
 /// <returns>True if the model system was removed successfully.</returns>
 public bool RemoveModelSystem(int index, ref string error)
 {
     lock (EditingSessionsLock)
     {
         if(index < 0 | index >= this.Project.ModelSystemStructure.Count)
         {
             error = "The index is invalid.";
             return false;
         }
         if(EditingSessions[index].Session != null)
         {
             error = "Unable to remove the model system. It is currently being edited.";
             return false;
         }
         if(!this.Project.RemoveModelSystem(index, ref error))
         {
             return false;
         }
         var temp = new SessionData[EditingSessions.Length - 1];
         Array.Copy(EditingSessions, temp, index);
         Array.Copy(EditingSessions, index + 1, temp, index, EditingSessions.Length - index - 1);
         EditingSessions = temp;
     }
     return true;
 }
Пример #43
0
        public static void OpenScpSession(SessionData session)
        {
            Log.InfoFormat("Opening scp session, id={0}", session == null ? "" : session.SessionId);
            if (!IsScpEnabled)
            {
                SuperPuTTY.ReportStatus("Could not open session, pscp not found: {0} [SCP]", session.SessionId);
            }
            else if (session != null)
            {
                PscpBrowserPanel panel = new PscpBrowserPanel(
                    session, new PscpOptions { PscpLocation = Settings.PscpExe },
                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                ApplyDockRestrictions(panel);
                ApplyIconForWindow(panel, session);
                panel.Show(MainForm.DockPanel, session.LastDockstate);

                SuperPuTTY.ReportStatus("Opened session: {0} [SCP]", session.SessionId);
            }
            else
            {
                Log.Warn("Could not open null session");
            }
        }
Пример #44
0
        public void TestBugWithCircuralReferences_StrengthTraining()
        {
            var profile1 = (ProfileDTO)profiles[0].Tag;
            var exercise = CreateExercise(Session, null, "ex1", "ex1");
            //create some training day entries
            var day = new TrainingDay(DateTime.Now.AddDays(-2));

            day.Profile = profiles[0];
            var sizeEntry = new StrengthTrainingEntry();

            sizeEntry.MyPlace = GetDefaultMyPlace(profiles[0]);
            day.AddEntry(sizeEntry);
            var strengthItem = new StrengthTrainingItem();

            strengthItem.Exercise = exercise;
            sizeEntry.AddEntry(strengthItem);
            var set = new Serie();

            strengthItem.AddSerie(set);
            set = new Serie();
            strengthItem.AddSerie(set);
            strengthItem          = new StrengthTrainingItem();
            strengthItem.Exercise = exercise;
            sizeEntry.AddEntry(strengthItem);
            set = new Serie();
            strengthItem.AddSerie(set);
            set = new Serie();
            strengthItem.AddSerie(set);
            Session.Save(day);
            trainingDays.Add(day);

            day               = new TrainingDay(DateTime.Now.AddDays(-1));
            day.Profile       = profiles[0];
            sizeEntry         = new StrengthTrainingEntry();
            sizeEntry.MyPlace = GetDefaultMyPlace(profiles[0]);
            day.AddEntry(sizeEntry);
            strengthItem          = new StrengthTrainingItem();
            strengthItem.Exercise = exercise;
            sizeEntry.AddEntry(strengthItem);
            set = new Serie();
            strengthItem.AddSerie(set);
            set = new Serie();
            strengthItem.AddSerie(set);
            strengthItem          = new StrengthTrainingItem();
            strengthItem.Exercise = exercise;
            sizeEntry.AddEntry(strengthItem);
            set = new Serie();
            strengthItem.AddSerie(set);
            set = new Serie();
            strengthItem.AddSerie(set);
            Session.Save(day);
            trainingDays.Add(day);

            SessionData data = CreateNewSession(profile1, ClientInformation);
            WorkoutDaysSearchCriteria searchCriteria = new WorkoutDaysSearchCriteria();

            searchCriteria.UserId = profiles[0].GlobalId;
            PagedResult <TrainingDayDTO> days = null;

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                days = Service.GetTrainingDays(data.Token, searchCriteria,
                                               new PartialRetrievingInfo()
                {
                    PageSize = PartialRetrievingInfo.AllElementsPageSize
                });
            });
            foreach (var item in ((StrengthTrainingEntryDTO)days.Items[5].Objects.ElementAt(0)).Entries)
            {
                Assert.AreEqual(days.Items[5].Objects.ElementAt(0), item.StrengthTrainingEntry);
                foreach (var tSet in item.Series)
                {
                    Assert.AreEqual(item, tSet.StrengthTrainingItem);
                }
            }

            foreach (var item in ((StrengthTrainingEntryDTO)days.Items[6].Objects.ElementAt(0)).Entries)
            {
                Assert.AreEqual(days.Items[6].Objects.ElementAt(0), item.StrengthTrainingEntry);
                foreach (var tSet in item.Series)
                {
                    Assert.AreEqual(item, tSet.StrengthTrainingItem);
                }
            }
        }
Пример #45
0
        static void OpenScpSessionOld(SessionData session)
        {
            Log.InfoFormat("Opening scp session, id={0}", session == null ? "" : session.SessionId);
            if (!IsScpEnabled)
            {
                SuperPuTTY.ReportStatus("Could not open session, pscp not found: {0} [SCP]", session.SessionId);
            }
            else if (session != null)
            {
                RemoteFileListPanel panel = null;
                bool cancelShow = false;
                if (session != null)
                {
                    PuttyClosedCallback callback = delegate(bool error)
                    {
                        cancelShow = error;
                    };
                    PscpTransfer xfer = new PscpTransfer(session);
                    xfer.PuttyClosed = callback;

                    panel = new RemoteFileListPanel(xfer, SuperPuTTY.MainForm.DockPanel, session);
                    ApplyDockRestrictions(panel);
                    ApplyIconForWindow(panel, session);
                    if (!cancelShow)
                    {
                        panel.Show(MainForm.DockPanel, session.LastDockstate);
                    }
                }

                SuperPuTTY.ReportStatus("Opened session: {0} [SCP]", session.SessionId);
            }
            else
            {
                Log.Warn("Could not open null session");
            }
        }
Пример #46
0
 protected override HElement GetElement(SessionData sessionData) => Main.GetPage(nameof(CreateProject), GetElements(sessionData));
Пример #47
0
    /**************************************************************************
     *      Selected Element Methods                                          *
     **************************************************************************/
    private static SessionData updateSelectedElement(string region, string id, string action, string password, string barcode, string minutes)
    {
        string commandText = getCommandText(region, id, action);
        SessionData SelectedElementData = new SessionData();
        try
        {
            using (MySqlConnection con = new MySqlConnection(ConnectionString))
            using (MySqlCommand cmd = new MySqlCommand(commandText, con))
            {

                if (action == "start")
                {
                    if (barcode == "none") { barcode = "Staff"; }
                    cmd.Parameters.AddWithValue("password", getPassword());
                    cmd.Parameters.AddWithValue("barcode", barcode);
                    logStats(id, region);
                }

                if (action == "renew")
                {
                    cmd.Parameters.AddWithValue("minutes", minutes);
                    logStats(id, region);
                }

                cmd.Parameters.AddWithValue("id", id);
                cmd.Parameters.AddWithValue("region", region);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

            }

            try
            {
                commandText = "SELECT * FROM kiosk WHERE region = @region AND id = @id;";
                using (MySqlConnection con = new MySqlConnection(ConnectionString))
                using (MySqlCommand cmd = new MySqlCommand(commandText, con))
                {
                    cmd.Parameters.AddWithValue("region", region);
                    cmd.Parameters.AddWithValue("id", id);
                    con.Open();
                    MySqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        SelectedElementData.status = rdr["status"].ToString();
                        SelectedElementData.minutes = Convert.ToInt32(rdr["minutes"]);
                        SelectedElementData.barcode = rdr["barcode"].ToString();
                        SelectedElementData.message = rdr["message"].ToString();
                        SelectedElementData.password = rdr["password"].ToString();
                        SelectedElementData.region = rdr["region"].ToString();
                        SelectedElementData.id = Convert.ToInt32(rdr["id"]);

                    }
                    con.Close();
                }
            }
            catch (Exception)
            {
                SelectedElementData.id = -1;
                SelectedElementData.error = "There was an error completing your last request!  There server may be unavailable!";

            }
        }

        catch (Exception ex)
        {
            SelectedElementData.id = -1;
            SelectedElementData.error = "There was an error completing your last request!  There server may be unavailable!";

        }

        return SelectedElementData;
    }
Пример #48
0
        void TryConnectFromToolbar()
        {
            String host = this.tbTxtBoxHost.Text;
            String protoString = (string)this.tbComboProtocol.SelectedItem;

            if (!String.IsNullOrEmpty(host))
            {
                HostConnectionString connStr = new HostConnectionString(host);
                bool isScp = "SCP" == protoString;
                ConnectionProtocol proto = isScp
                    ? ConnectionProtocol.SSH
                    : connStr.Protocol.GetValueOrDefault((ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), protoString));
                SessionData session = new SessionData
                {
                    Host = connStr.Host,
                    SessionName = connStr.Host,
                    SessionId = SuperPuTTY.MakeUniqueSessionId(SessionData.CombineSessionIds("ConnectBar", connStr.Host)),
                    Proto = proto,
                    Port = connStr.Port.GetValueOrDefault(dlgEditSession.GetDefaultPort(proto)),
                    Username = this.tbTxtBoxLogin.Text,
                    Password = this.tbTxtBoxPassword.Text,
                    PuttySession = (string)this.tbComboSession.SelectedItem
                };
                SuperPuTTY.OpenSession(new SessionDataStartInfo { Session = session, UseScp = isScp });
                oldHostName = this.tbTxtBoxHost.Text;
                RefreshConnectionToolbarData();
            }
        }
Пример #49
0
 public PscpTransfer(SessionData session)
 {
     m_Session = session;
     m_Login = new dlgLogin(m_Session);
 }
Пример #50
0
        public void GetApplicationName_ManyItems()
        {
            var apiKey = new APIKey();

            apiKey.ApiKey           = Guid.NewGuid();
            apiKey.ApplicationName  = "UnitTest";
            apiKey.EMail            = "*****@*****.**";
            apiKey.RegisterDateTime = DateTime.UtcNow;
            insertToDatabase(apiKey);
            LoginData loginData = new LoginData();

            loginData.ApiKey              = apiKey;
            loginData.ApplicationVersion  = "1.0.0";
            loginData.LoginDateTime       = DateTime.UtcNow;
            loginData.ApplicationLanguage = "en";
            loginData.PlatformVersion     = "NUnit";
            insertToDatabase(loginData);
            trainingDays[0].Objects.ElementAt(0).LoginData = loginData;
            insertToDatabase(trainingDays[0]);

            apiKey                  = new APIKey();
            apiKey.ApiKey           = Guid.NewGuid();
            apiKey.ApplicationName  = "UnitTest";
            apiKey.EMail            = "*****@*****.**";
            apiKey.RegisterDateTime = DateTime.UtcNow;
            insertToDatabase(apiKey);
            loginData                     = new LoginData();
            loginData.ApiKey              = apiKey;
            loginData.ApplicationVersion  = "1.0.0";
            loginData.LoginDateTime       = DateTime.UtcNow;
            loginData.ApplicationLanguage = "en";
            loginData.PlatformVersion     = "NUnit";
            insertToDatabase(loginData);
            trainingDays[1].Objects.ElementAt(0).LoginData = loginData;
            insertToDatabase(trainingDays[1]);

            apiKey                  = new APIKey();
            apiKey.ApiKey           = Guid.NewGuid();
            apiKey.ApplicationName  = "UnitTest";
            apiKey.EMail            = "*****@*****.**";
            apiKey.RegisterDateTime = DateTime.UtcNow;
            insertToDatabase(apiKey);
            loginData                     = new LoginData();
            loginData.ApiKey              = apiKey;
            loginData.ApplicationVersion  = "1.0.0";
            loginData.LoginDateTime       = DateTime.UtcNow;
            loginData.ApplicationLanguage = "en";
            loginData.PlatformVersion     = "NUnit";
            insertToDatabase(loginData);
            trainingDays[2].Objects.ElementAt(0).LoginData = loginData;
            insertToDatabase(trainingDays[2]);

            apiKey                  = new APIKey();
            apiKey.ApiKey           = Guid.NewGuid();
            apiKey.ApplicationName  = "UnitTest";
            apiKey.EMail            = "*****@*****.**";
            apiKey.RegisterDateTime = DateTime.UtcNow;
            insertToDatabase(apiKey);
            loginData                     = new LoginData();
            loginData.ApiKey              = apiKey;
            loginData.ApplicationVersion  = "1.0.0";
            loginData.LoginDateTime       = DateTime.UtcNow;
            loginData.ApplicationLanguage = "en";
            loginData.PlatformVersion     = "NUnit";
            insertToDatabase(loginData);
            trainingDays[3].Objects.ElementAt(0).LoginData = loginData;
            insertToDatabase(trainingDays[3]);

            apiKey                  = new APIKey();
            apiKey.ApiKey           = Guid.NewGuid();
            apiKey.ApplicationName  = "UnitTest";
            apiKey.EMail            = "*****@*****.**";
            apiKey.RegisterDateTime = DateTime.UtcNow;
            insertToDatabase(apiKey);
            loginData                     = new LoginData();
            loginData.ApiKey              = apiKey;
            loginData.ApplicationVersion  = "1.0.0";
            loginData.LoginDateTime       = DateTime.UtcNow;
            loginData.ApplicationLanguage = "en";
            loginData.PlatformVersion     = "NUnit";
            insertToDatabase(loginData);
            trainingDays[4].Objects.ElementAt(0).LoginData = loginData;
            insertToDatabase(trainingDays[4]);
            var profile1 = (ProfileDTO)profiles[0].Tag;

            SessionData data = CreateNewSession(profile1, ClientInformation);
            WorkoutDaysSearchCriteria    searchCriteria = new WorkoutDaysSearchCriteria();
            PagedResult <TrainingDayDTO> days           = null;

            RunServiceMethod(delegate(InternalBodyArchitectService Service)
            {
                Service.Configuration.CurrentApiKey = key;
                days = Service.GetTrainingDays(data.Token, searchCriteria, new PartialRetrievingInfo()
                {
                    PageSize = PartialRetrievingInfo.AllElementsPageSize
                });
            });
            Assert.AreEqual(apiKey.ApplicationName, days.Items[0].Objects.ElementAt(0).ApplicationName);
        }
Пример #51
0
    public static SessionData getElementForScanner(string barcode)
    {
        SessionData newSession = new SessionData();
        List<SessionData> availableSessions = new List<SessionData>();

        //  see what regions the patron has access to - on hold

        try
        {
            string cmdText = "SELECT * FROM kiosk WHERE status='locked' AND registration_status='registered';";  //  and limited by patron type - later
            using (MySqlConnection con = new MySqlConnection(ConnectionString))
            using (MySqlCommand cmd = new MySqlCommand(cmdText, con))
            {
                con.Open();
                MySqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        availableSessions.Add(new SessionData
                        {
                            status = rdr["status"].ToString(),
                            minutes = Convert.ToInt32(rdr["minutes"]),
                            barcode = rdr["barcode"].ToString(),
                            message = rdr["message"].ToString(),
                            password = rdr["password"].ToString(),
                            region = rdr["region"].ToString(),
                            id = Convert.ToInt32(rdr["id"])
                        });
                    }
                }
                else
                {
                    return new SessionData { id = -1, error = "It appears that all of the computers are currently in use!" };
                }
            }
        }
        catch (Exception ex)
        {
            return new SessionData { id = -1, error = ex.Message };
        }

        Random random = new Random();
        newSession = availableSessions[random.Next(0, availableSessions.Count - 1)];
        newSession.password = getPassword();
        newSession.status = "unlocked";
        newSession.barcode = barcode;

        try
        {
            string cmdText = "UPDATE kiosk SET status='unlocked', minutes='60', password=@password, barcode=@barcode WHERE id=@id AND region=@region;";
            using (MySqlConnection con = new MySqlConnection(ConnectionString))
            using (MySqlCommand cmd = new MySqlCommand(cmdText, con))
            {
                cmd.Parameters.AddWithValue("password", newSession.password);
                cmd.Parameters.AddWithValue("barcode", newSession.barcode);
                cmd.Parameters.AddWithValue("id", newSession.id);
                cmd.Parameters.AddWithValue("region", newSession.region);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            logStats(newSession.id.ToString(), newSession.region);
        }
        catch (Exception)
        {
            return new SessionData { id = -1, error = "Could not connect to the database!  Please see a librarian!" };
        }

        return newSession;
    }
Пример #52
0
        public dlgEditSession(SessionData session, ImageList iconList)
        {
            Session = session;
            InitializeComponent();

            // get putty saved settings from the registry to populate
            // the dropdown
            PopulatePuttySettings();

            if (!String.IsNullOrEmpty(Session.SessionName))
            {
                this.Text = "Edit session: " + session.SessionName;
                this.textBoxSessionName.Text = Session.SessionName;
                this.textBoxHostname.Text = Session.Host;
                this.textBoxPort.Text = Session.Port.ToString();
                this.textBoxExtraArgs.Text = Session.ExtraArgs;
                this.textBoxUsername.Text = Session.Username;

                switch (Session.Proto)
                {
                    case ConnectionProtocol.Raw:
                        radioButtonRaw.Checked = true;
                        break;
                    case ConnectionProtocol.Rlogin:
                        radioButtonRlogin.Checked = true;
                        break;
                    case ConnectionProtocol.Serial:
                        radioButtonSerial.Checked = true;
                        break;
                    case ConnectionProtocol.SSH:
                        radioButtonSSH.Checked = true;
                        break;
                    case ConnectionProtocol.Telnet:
                        radioButtonTelnet.Checked = true;
                        break;
                    case ConnectionProtocol.Cygterm:
                        radioButtonCygterm.Checked = true;
                        break;
                    case ConnectionProtocol.Mintty:
                        radioButtonMintty.Checked = true;
                        break;
                    default:
                        radioButtonSSH.Checked = true;
                        break;
                }

                foreach(String settings in this.comboBoxPuttyProfile.Items){
                    if (settings == session.PuttySession)
                    {
                        this.comboBoxPuttyProfile.SelectedItem = settings;
                        break;
                    }
                }

                this.buttonSave.Enabled = true;
            }
            else
            {
                this.Text = "Create new session";
                radioButtonSSH.Checked = true;
                this.buttonSave.Enabled = false;
            }

            // Setup icon chooser
            this.buttonImageSelect.ImageList = iconList;
            this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey)
                ? SessionTreeview.ImageKeySession
                : Session.ImageKey;
            this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);

            this.isInitialized = true;
        }
Пример #53
0
        public void SessionAdd(CQGSessions sessions, string symbol)
        {
            if (_shouldStop) return;
            try
            {
                foreach (CQGSession session in sessions)
                {
                    var one = new SessionData
                    {
                        StartTime = session.StartTime,
                        EndTime = session.EndTime,
                        DayOfWeek = session.WorkingWeekDays,
                        Symbol = symbol,
                        DayStartsYesterday =  session.DayStartsYesterday
                    };
                    _listSession.Add(one);

                    DatabaseManager.AddToSessionTable(symbol, symbol, session.StartTime, session.EndTime, "Open",
                        GetSessionWorkingDays(session.WorkingWeekDays), session.DayStartsYesterday, session.PrimaryFlag, session.Number, DateTime.Now);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _logger.LogAdd("SessionAdd. " + ex.Message, Category.Error);
            }

            _aSemaphoreSessions.Release();
        }
Пример #54
0
        public void InitializePage(string functionName, string pageKey, string itemKey, SessionData session, string URL, string Port)
        {
            this.FunctionName = functionName;
            this.KeyOfPage    = pageKey;
            this.itemKey      = itemKey;
            this.sessionData  = session;
            this.URL          = URL;
            port = Port;

            this.InitializePage();
        }
Пример #55
0
 protected override HElement GetElement(SessionData sessionData)
 {
     return(GetPage("TODO", GetElements(sessionData)));
 }
Пример #56
0
 /// <summary>
 /// Creates new SessionData, always called AFTER InitData
 /// </summary>
 public static void StartNewSession()
 {
     sessionData = new SessionData();
 }
Пример #57
0
        static string MakeArgs(SessionData session, bool includePassword, string path)
        {
            string args = "-ls "; // default arguments
            args += (!String.IsNullOrEmpty(session.PuttySession)) ? "-load \"" + session.PuttySession + "\" " : "";
            args += (!String.IsNullOrEmpty(session.Password) && session.Password.Length > 0)
                ? "-pw " + (includePassword ? session.Password : "******") + " "
                : "";
            args += "-P " + session.Port + " ";
            args += (!String.IsNullOrEmpty(session.Username)) ? session.Username + "@" : "";
            args += session.Host + ":" + path;

            return args;
        }
Пример #58
0
        private IEnumerable <HElement> GetElements(SessionData sessionData)
        {
            if (!sessionData.KnownUser)
            {
                if (sessionData.HttpPostVariables.ContainsKey("username") && sessionData.HttpPostVariables.ContainsKey("password"))
                {
                    string username = sessionData.GetHttpPostValue("username");
                    string password = sessionData.GetHttpPostValue("password");

                    if (User.Users.ContainsKey(username))
                    {
                        User u = User.Users[username];

                        if (u.Password.IsValid(password))
                        {
                            (sessionData as HttpSessionData).RegisterUser(username);
                            sessionData.SetUserVariable(nameof(User), u);
                            yield return(new HScript(ScriptCollection.GetPageReloadInMilliseconds, 0));

                            yield break;
                        }
                    }

                    yield return(new HText("The credentials were invalid."));
                }

                yield return(new HForm("/")
                {
                    Elements =
                    {
                        new HText("Username"),
                        new HTextInput("username",    "",           "Username"),
                        new HNewLine(),
                        new HText("Password"),
                        new HPasswordInput("password","password"),
                        new HNewLine(),
                        new HButton("Login",          HButton.EButtonType.submit)
                    }
                });

                yield break;
            }
            else
            {
                User user = sessionData.GetUserVariable <User>(nameof(User));

                if (user.IsAdmin)
                {
                    yield return(new HButton("Create new project", nameof(CreateProject)));

                    yield return(new HLine());
                }

                yield return(new HButton("Manage User Preferences", nameof(ViewUser)));

                foreach (var p in Project.Projects)
                {
                    if (p.Value.IsAccessible(user))
                    {
                        yield return(new HLink(p.Key, $"{nameof(ViewProject)}?id={p.Value.Name}"));

                        yield return(new HNewLine());
                    }
                }
            }
        }
Пример #59
0
        private static async Task <string> GetLoginTicket(string username, string password, System.Net.Http.HttpClient tempHttpClient, SessionData sessionData)
        {
            HttpResponseMessage loginResp;
            var loginRequest = GenerateLoginRequest(sessionData, username, password);

            using (var formUrlEncodedContent = new FormUrlEncodedContent(loginRequest))
            {
                loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl, formUrlEncodedContent).ConfigureAwait(false);
            }

            var ticketId = ExtractTicketFromResponse(loginResp);

            return(ticketId);
        }
 public void Initialize(UiState uiState, SessionData sessionData)
 {
     this.uiState     = uiState;
     this.sessionData = sessionData;
 }