Exemplo n.º 1
0
        public IHttpActionResult AddSession([FromBody] NewSession newSession)
        {
            if (newSession is null)
            {
                return(NotFound());
            }

            // Generate Session & Add to database
            var NewSession = new Session();

            NewSession.SessionId             = Guid.NewGuid();
            NewSession.SessionCompletionTime = newSession.SessionCompletionTime;
            NewSession.SessionDescription    = newSession.SessionDescription;
            NewSession.SessionGains          = newSession.SessionGains;
            NewSession.SessionReward         = newSession.SessionReward;
            NewSession.SessionTitle          = newSession.SessionTitle;
            NewSession.SessionVideo          = newSession.SessionVideo;
            NewSession.SessionXpReward       = newSession.SessionXpReward;
            NewSession.TopicId      = new Guid(newSession.TopicId);
            NewSession.LevelId      = new Guid(newSession.LevelId);
            NewSession.SessionOrder = newSession.SessionOrder;

            // Add to database
            WmData.Sessions.Add(NewSession);
            WmData.SaveChanges();

            // Return success message
            return(Ok("Session Added"));
        }
Exemplo n.º 2
0
        public void TestInverseSql()
        {
            var class1 = InitClasses();
            var s1     = class1.Students[0];
            var s2     = class1.Students[1];
            var class2 = new Class()
            {
                ClassName = "Class2"
            };

            s1.Class = class2;
            s1.Name  = "班级2的学生";
            s1.Class = class2;
            s2.Class = class2;
            Debug.WriteLine("--Begin Save--");
            Session.SaveOrUpdate(class1);
            Session.SaveOrUpdate(class2);
            Debug.WriteLine("--End Save--");
            Session.Flush();
            Debug.WriteLine("--End Flush--");
            var c1 = NewSession.Get <Class>(class1.Id);

            Debug.WriteLine("Class 1 Student count:" + c1.Students.Count);
            var c2 = NewSession.Get <Class>(class2.Id);

            Debug.WriteLine("Class 2 Student count:" + c2.Students.Count);
        }
Exemplo n.º 3
0
        /// <summary>收到新连接时处理</summary>
        /// <param name="client"></param>
        protected virtual void OnAccept(Socket client)
        {
            var session = CreateSession(client);

            // 设置心跳时间
            client.SetTcpKeepAlive(true);

            if (_Sessions.Add(session))
            {
                //session.ID = g_ID++;
                // 会话改为原子操作,避免多线程冲突
                session.ID = Interlocked.Increment(ref g_ID);
                //WriteLog("{0}新会话 {1}", this, client.Client.RemoteEndPoint);
                session.WriteLog("New {0}", session.Remote.EndPoint);

                if (StatSession != null)
                {
                    StatSession.Increment(1);
                }

                NewSession?.Invoke(this, new SessionEventArgs {
                    Session = session
                });

                //// 自动开始异步接收处理
                //if (AutoReceiveAsync)
                session.ReceiveAsync();
            }
        }
Exemplo n.º 4
0
        public void TestInsert3ClassData()
        {
            Place p = new Place()
            {
                Address = "place", Description = "this is a place", Size = 100
            };

            Session.SaveOrUpdate(p);
            Classroom c = new Classroom()
            {
                Address = "place", Description = "this is a place", Size = 100, RoomNumber = "301"
            };

            Session.SaveOrUpdate(c);
            Lab l = new Lab()
            {
                Address = "place", Description = "this is a place", Size = 100, LabSubject = "Physical"
            };

            Session.SaveOrUpdate(l);
            Session.Flush();

            var list = NewSession.QueryOver <Place>().List();

            Assert.Greater(list.Count, 0);
            foreach (var place in list)
            {
                Debug.WriteLine(place.GetType().ToString());
            }
        }
Exemplo n.º 5
0
        public async void ListenAsync(string ip, int port)
        {
            if (Listening)
            {
                throw new Exception("Listening");
            }
            Listening = true;

            server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);
            server.Start();
            ListeningStarted(this, server);
            Env.Print($"listening: {server.LocalEndpoint.ToString()}");
            try
            {
                while (true)
                {
                    Env.Print("waiting for a connection");
                    var client = await server.AcceptTcpClientAsync();

                    Env.Print("one incoming tcp connection");

                    var session = new TcpClientSession(client);
                    NewSession.Invoke(this, session);
                    TcpClientAccepted?.Invoke(this, session);
                    session.Receive();
                }
            }
            catch (Exception ex)
            {
                Env.Print(ex.Message);
            }
        }
Exemplo n.º 6
0
        /*接收新的连接*/
        private void OnAcceptNewConnection(object sender, SocketAsyncEventArgs e)
        {
            /*新连接的socket对象*/
            var socket = e.AcceptSocket;

            /*继续接收*/
            startAccept(e);

            /*连接数+1*/
            Interlocked.Increment(ref connectionCount);


            /*尝试取出一个异步完成套接字*/
            if (!receiveAsyncEventQueue.TryDequeue(out var socketReceiveAsync))
            {
                socketReceiveAsync            = new SocketAsyncEventArgs();
                socketReceiveAsync.Completed += SocketAsync_Receive_Completed;
                socketReceiveAsync.SetBuffer(new byte[1024], 0, 1024);
            }

            /*创建一个客户端*/
            var session = new TSession
            {
                Socket     = socket,
                ReceiveSAE = socketReceiveAsync,
                APPServer  = this,
            };

            socketReceiveAsync.UserToken = session;
            NewSession?.Invoke(this, session);
            OnNewSession(session);

            StartReceive(session);
        }
Exemplo n.º 7
0
        public void TestSelect()
        {
            UserA a = new UserA()
            {
                Name = "User A", Files = new List <UserAFile> {
                    new UserAFile()
                    {
                        FileName = "About A.txt"
                    }, new UserAFile()
                    {
                        FileName = "Only for User A"
                    }
                }
            };
            UserB b = new UserB()
            {
                Number = "NumberB"
            };

            Session.Save(a);
            Session.Save(b);
            Session.Flush();
            var userb = NewSession.Get <UserB>(b.Id);

            Assert.AreEqual(userb.Files.Count, 0);
        }
Exemplo n.º 8
0
        public void ConcreteTableTestSearchSubClassByRootClassRepository()
        {
            var ems = NewSession.QueryOver <Person>().Where(a => a.GetType() == typeof(Student)).List();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 9
0
        static void HandleNewSessionCreated(BinaryReader messageReader, TgSystemMessageHandlerContext ctx)
        {
            messageReader.ReadInt32();
            var newSession = NewSession.DeserializeTag(messageReader);

            ctx.NewSalt = newSession.ServerSalt;

            TgTrace.Trace("NewSession: " + newSession);
        }
Exemplo n.º 10
0
        public void SingleTableTestSearchSubClass()
        {
            var ts = NewSession.QueryOver <Teacher>().List();

            foreach (var teacher in ts)
            {
                Debug.WriteLine(teacher);
            }
        }
Exemplo n.º 11
0
        public void SingleTableTestSearchSubClassByRootClassRepository()
        {
            var ems = NewSession.QueryOver <Employee>().Where(a => a.GetType() == typeof(Teacher)).List();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 12
0
        public void ConcreteTableTestSearchSubClass()
        {
            var ts = NewSession.QueryOver <Student>().List();

            foreach (var s in ts)
            {
                Debug.WriteLine(s);
            }
        }
Exemplo n.º 13
0
        public void ClassTableTestSearchSubClass()
        {
            var ts = NewSession.QueryOver <Classroom>().List();

            foreach (var s in ts)
            {
                Debug.WriteLine(s);
            }
        }
Exemplo n.º 14
0
        public void SingleTableTestHqlSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateQuery("from Employee where Type='Teacher'");
            var ems = cri.List <Employee>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 15
0
        /// <summary>接受连接时,对于Udp是收到数据时(同时触发OnReceived)。</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Server_NewSession(Object sender, SessionEventArgs e)
        {
            var session = e.Session;

            var ns = OnNewSession(session);

            NewSession?.Invoke(sender, new NetSessionEventArgs {
                Session = ns
            });
        }
Exemplo n.º 16
0
        public void ClassTableTestHqlSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateQuery("from Classroom'");
            var ems = cri.List <Classroom>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 17
0
        public void ConcreteTableTestHqlSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateQuery("from Person where type='Student'");
            var ems = cri.List <Student>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 18
0
        public void ClassTableTestCritialSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateCriteria <Place>();

            cri = cri.Add(Expression.Eq("class", typeof(Classroom)));
            var ems = cri.List <Classroom>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 19
0
        public void SingleTableTestCritialSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateCriteria <Employee>();

            cri = cri.Add(Expression.Eq("class", "Teacher"));
            var ems = cri.List <Employee>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 20
0
        public void ConcreteTableTestCritialSearchSubClassByRootClassRepository()
        {
            var cri = NewSession.CreateCriteria <Person>();

            cri = cri.Add(Expression.Eq("class", typeof(Student)));
            var ems = cri.List <Student>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 21
0
        public void TestSearchEmployee()
        {
            var doors = NewSession.QueryOver <Education>()
                        .Fetch(a => a.Employee).Eager
                        .List <Education>();

            foreach (var employee in doors)
            {
                // foreach (var employee in doorKey.Employees)
                {
                    Debug.WriteLine(employee.Employee.GetType() + " ----" + employee.ToString());
                }
            }
        }
Exemplo n.º 22
0
        public void SingleTableTestSearchSubClassByAssociation()
        {
            Employee e   = null;
            var      ems = NewSession.QueryOver <DoorKey>()
                           .JoinAlias(d => d.Employees, () => e)
                           .Where(() => e.GetType() == typeof(Teacher))
                           .Select(d => e.Name)
                           .List <string>();

            foreach (var employee in ems)
            {
                Debug.WriteLine(employee);
            }
        }
Exemplo n.º 23
0
        internal static void OnSessionCreated(NativeInterfaces.IAudioSessionControl newSession)
        {
            if (newSession == null)
            {
                return;
            }

            var args = new AudioSessionCreatedEventArgs(new AudioSession((NativeInterfaces.IAudioSessionControl2)newSession));

            NewSession?.Invoke(args);

            if (args.Release)
            {
                args.Session.Dispose();
            }
        }
Exemplo n.º 24
0
        public void TestM2MInverse()
        {
            Emp e1 = new Emp()
            {
                Name = "E1"
            };
            Emp e2 = new Emp()
            {
                Name = "E2"
            };
            Award a1 = new Award()
            {
                Name = "A1"
            };
            Award a2 = new Award()
            {
                Name = "A2"
            };

            //e1.Awards=new List<Award>(){a1,a2};
            a1.Emps = new List <Emp>()
            {
                e1
            };
            a2.Emps = new List <Emp>()
            {
                e1
            };
            Debug.WriteLine("---Begin Save---");


            Session.SaveOrUpdate(e1);
            Session.SaveOrUpdate(e2);
            Session.SaveOrUpdate(a1);
            Session.SaveOrUpdate(a2);
            Debug.WriteLine("---Begin Flush---");
            Session.Flush();
            Debug.WriteLine("---End Flush---");
            var award1 = NewSession.Get <Award>(a1.Id);

            foreach (var emp in award1.Emps)
            {
                Debug.WriteLine(emp);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 接收新的连接
        /// </summary>
        private void ChannelActive(IChannelHandlerContext context)
        {
            /*连接数+1*/
            Interlocked.Increment(ref connectionCount);

            var channelId = context.Channel.Id.AsShortText();
            var session   = new TSession()
            {
                SessionId = channelId,
                Channel   = context.Channel
            };

            if (allSession.TryAdd(channelId, session))
            {
                NewSession?.Invoke(this, session);
                OnNewSession(session);
            }
        }
        public async Task <Session> CreateSession([FromBody] NewSession newSession)
        {
            Session session = new Session()
            {
                id          = Guid.NewGuid().ToString(),
                playerId    = newSession.PlayerId,
                StartTime   = DateTime.Now.AddSeconds(-newSession.LengthInSeconds),
                EndTime     = DateTime.Now,
                Starts      = newSession.Wins + newSession.Deaths,
                Wins        = newSession.Wins,
                Deaths      = newSession.Deaths,
                StartString = DateTime.Now.Year + ":" + DateTime.Now.Month.ToString("00") + ":"
                              + DateTime.Now.Day.ToString("00") + ":" + DateTime.Now.Hour.ToString("00")
                              + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00")
            };
            await _repository.UpdateSessionCount(newSession.PlayerId);

            session.LengthInSeconds = (int)session.EndTime.Subtract(session.StartTime).TotalSeconds;

            return(await _repository.CreateSession(session));
        }
Exemplo n.º 27
0
        public void TestSearchTeacher()
        {
            var em = NewSession.QueryOver <Employee>().Where(e => e.Id == t1.Id).SingleOrDefault();

            Debug.WriteLine(em.GetType() + "--" + em.ToString());
        }
 /// <summary>
 /// Raise the <see cref="NewSession"/> event
 /// </summary>
 /// <param name="eventArgs"></param>
 private void NewSessionEvent(EventArgs eventArgs)
 {
     NewSession?.Invoke(sender: this, e: eventArgs);
 }
Exemplo n.º 29
0
        /// <summary>创建会话</summary>
        /// <param name="remoteEP"></param>
        /// <returns></returns>
        public virtual ISocketSession CreateSession(IPEndPoint remoteEP)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            var sessions = _Sessions;

            if (sessions == null)
            {
                return(null);
            }

            // 平均执行耗时260.80ns,其中55%花在sessions.Get上面,Get里面有加锁操作

            if (!Active)
            {
                // 根据目标地址适配本地IPv4/IPv6
                Local.Address = Local.Address.GetRightAny(remoteEP.AddressFamily);

                if (!Open())
                {
                    return(null);
                }
            }

            // 需要查找已有会话,已有会话不存在时才创建新会话
            var session = sessions.Get(remoteEP + "");

            if (session != null)
            {
                return(session);
            }

            // 相同远程地址可能同时发来多个数据包,而底层采取多线程方式同时调度,导致创建多个会话
            lock (sessions)
            {
                // 需要查找已有会话,已有会话不存在时才创建新会话
                session = sessions.Get(remoteEP + "");
                if (session != null)
                {
                    return(session);
                }

                var us = new UdpSession(this, remoteEP);
                us.Log        = Log;
                us.LogSend    = LogSend;
                us.LogReceive = LogReceive;
                // UDP不好分会话统计
                //us.StatSend.Parent = StatSend;
                //us.StatReceive.Parent = StatReceive;
                us.Packet = SessionPacket?.Create();

                session = us;
                if (sessions.Add(session))
                {
                    //us.ID = g_ID++;
                    // 会话改为原子操作,避免多线程冲突
                    us.ID = Interlocked.Increment(ref g_ID);
                    us.Start();

                    if (StatSession != null)
                    {
                        StatSession.Increment(1);
                    }

                    // 触发新会话事件
                    NewSession?.Invoke(this, new SessionEventArgs {
                        Session = session
                    });
                }
            }

            return(session);
        }
Exemplo n.º 30
0
 internal void OnNewSession(IEntitySession session)
 {
     NewSession?.Invoke(session, new EntitySessionEventArgs(session));
 }
        private void btnStartEndSession_Click(object sender, EventArgs e)
        {
            if (cvSession == null ||
                cvSession.status.Equals("disconnected"))
            {
                if (!string.IsNullOrWhiteSpace(txtClientID.Text))
                {
                    var newSession = new NewSession
                                         {
                                             callerId = txtClientID.Text,
                                             callId = txtCallID.Text,
                                             newMessageUri = string.Empty,
                                             stateChangeUri = string.Empty
                                         };

                    Invoke((MethodInvoker)(() =>
                    {
                        toolStripStatusLabel1.Text = "Waiting for server at " + Settings.Default.ApiAddress + "...";
                        btnStartEndSession.Text = "Waiting";
                        btnStartEndSession.Enabled = false;
                    }));

                    Client.PostAsJsonAsync(SessionsUri.AbsoluteUri, newSession).ContinueWith(
                        responseTask =>
                        {
                            var errId = String.Format("POST {0} failed!", SessionsUri.AbsoluteUri);
                            if (responseTask.Exception != null)
                            {
                                UpdateUI(false);
                                displayHttpRequestError(responseTask.Exception, errId);
                            }
                            else if (responseTask.Result.StatusCode == HttpStatusCode.Created)
                            {
                                SessionUri = responseTask.Result.Headers.Location;
                                responseTask.Result.Content.ReadAsAsync<Session>(
                                    new List<MediaTypeFormatter> { jsonFormatter }).ContinueWith(
                                        contentTask =>
                                        {
                                            if (contentTask.Exception == null)
                                            {
                                                cvSession = contentTask.Result;
                                                if (cvSession != null)
                                                {
                                                    UpdateSessionInfo(cvSession);
                                                }
                                                else
                                                {
                                                    MessageBox.Show(
                                                        String.Format(
                                                            "POST {0} did not return recognizable content!",
                                                            SessionsUri.AbsoluteUri));
                                                }
                                                UpdateUI(cvSession != null &&
                                                         !cvSession.status.Equals("disconnected"));
                                            }
                                            else
                                            {
                                                UpdateUI(false);
                                                MessageBox.Show(
                                                    String.Format(
                                                        "Cannot read the content from POST {0}\nError: {1}",
                                                        SessionsUri.AbsoluteUri, contentTask.Exception.InnerException.Message));
                                            }
                                        }
                                    );
                            }
                            else
                            {
                                UpdateUI(false);
                                displayHttpResponseError(responseTask.Result, errId);
                            }
                        });
                }
                else
                {
                    MessageBox.Show("No Client ID!");
                }
            }
            else
            {
                Client.DeleteAsync(SessionUri).ContinueWith(
                    task =>
                        {
                            var errId = String.Format("DELETE {0} failed!", SessionUri.AbsoluteUri);
                            if (task.Exception != null)
                            {
                                displayHttpRequestError(task.Exception, errId);
                            }
                            else if (task.Result.IsSuccessStatusCode)
                            {
                                cvSession.status = "disconnected";
                                UpdateSessionInfo(cvSession);
                            }
                            else displayHttpResponseError(task.Result, errId);
                        });
            }
        }