public static void Right()
 {
     Connection connection = new Connection();
     connection.ConnectionString = "DataSource=//MyMachine";
     connection.Connect();
     connection.Disconnect();
 }
        private void btnTest_Click(object sender, EventArgs e)
        {
            txtInfo.Text = string.Empty;
            txtUserInfo.Text = string.Empty;
            txtPassport.Text = string.Empty;

            Connection con = new Connection();
            con.EnableSession = false;
            con.EnableSecureTunnel = true;
            SecurityToken stt = null;
            try
            {
                stt = this.GetSecurityToken();
                con.Connect(MainForm.CurrentProject.DevSite.AccessPoint, _contract.Name, stt);
                txtInfo.Text = "連線成功";                
            }
            catch (Exception ex)
            {
                txtInfo.Text = "連線失敗 : \n" + ex.Message;
                return;
            }
                        
            try
            {
                Envelope env = con.SendRequest("DS.Base.Connect", new Envelope());
                txtUserInfo.Text = env.Headers["UserInfo"];
                xmlSyntaxLanguage1.FormatDocument(txtUserInfo.Document);
            }
            catch 
            {               
            }
        }
Example #3
0
 static void Main(string[] args)
 {
     myList<byte> msgs;
     string strmsg;
     Connection cc = new Connection();
     cc.Connect();
     Connection sc = new Connection("chat.facebook.com");
     sc.Connect();
     while (true)
     {
         strmsg = "";
         msgs = cc.GetMessages();
         if ((msgs != null) && (msgs.Count > 0))
         {
             strmsg = ConvertMsgToString(msgs);
             sc.Send(msgs);
         }
         msgs = sc.GetMessages();
         if ((msgs != null) && (msgs.Count > 0))
         {
             strmsg = ConvertMsgToString(msgs);
             cc.Send(msgs);
         }
         if (strmsg.Length > 0)
         {
             Console.WriteLine(strmsg);
         }
         if (strmsg.Contains("proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
         {
             cc.StartTls();
             sc.StartTls();
         }
     }
 }
        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            using (Connection conn = new Connection("myConn"))
            {
                conn.Connect(textBoxServer.Text);
                conn.LogOn(textBoxUsername.Text, textBoxPassword.Text);

                DBObject dbObj = null;

                try
                {
                    int id = Convert.ToInt32(textBoxID.Text);
                    dbObj = conn.GetObject(new ObjectId(id));
                    if (dbObj == null) throw new Exception("Invalid object ID.");
                    if (!dbObj.IsGroup) throw new Exception("Object is not a group.");
                }

                catch (FormatException ex)
                {
                    MessageBox.Show("Enter a valid object ID.");
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }

                if (dbObj.ClassDefinition.Name == "CTemplateInstance") ProcessInstance(dbObj);
                else if (dbObj.ClassDefinition.Name == "CTemplate") ProcessTemplate(dbObj);

                conn.LogOff();
                conn.Disconnect();
            }
        }
        private void ImportFromSite()
        {
            err.Clear();
            if (string.IsNullOrWhiteSpace(txtAccessPoint.Text))
            {
                err.SetError(txtAccessPoint, "主機位置不可空白");
                return;
            }

            Connection connection = new Connection();
            connection.EnableSecureTunnel= true;
            try
            {
                connection.Connect(txtAccessPoint.Text, txtContract.Text, txtUserName.Text, txtPassword.Text);
            }
            catch (Exception ex)
            {
                err.SetError(txtAccessPoint, "主機連線失敗 : \n" + ex.Message);
                return;
            }

            XmlHelper h = new XmlHelper();
            h.AddElement(".","ApplicationName","shared");
            Envelope env = new Envelope(h);
            
            env = connection.SendRequest("Server.ExportApplication", env);
            h = new XmlHelper(env.Body);
            Console.WriteLine(h.XmlString);
            this.Import(h.GetElement("."));
        }
        /// <summary>
        /// 用Passport連線至AccessPoint,並傳回對應的連線資訊;並且會放到連線區中,之後可重覆使用。OK
        /// </summary>
        /// <param name="AccessPoint"></param>
        /// <returns></returns>
        public static Tuple<Connection, string> GetConnection(string AccessPoint, string ContractName)
        {
            if (mConnections == null)
                mConnections = new Dictionary<string, Connection>();

            if (mTimers == null)
                mTimers = new List<Timer>();

            if (mConnections.ContainsKey(AccessPoint))
                return new Tuple<Connection, string>(mConnections[AccessPoint], string.Empty);

            try
            {
                #region Connection一開始會用Passport連線,之後強制使用Session連線,並定期送Request確保Session不會過期
                Connection vConnection = new Connection();
                vConnection.EnableSession = true;
                vConnection.Connect(AccessPoint, ContractName, FISCA.Authentication.DSAServices.AccessPoint, FISCA.Authentication.DSAServices.AccessPoint);

                //Timer mTimer = new Timer(x =>
                //{
                //    vConnection.SendRequest("DS.Base.Connect", new Envelope());
                //}, null, 9000 * 60, 9000 * 60);

                //mTimers.Add(mTimer);

                mConnections.Add(AccessPoint, vConnection);
                #endregion

                return new Tuple<Connection, string>(vConnection, string.Empty);
            }
            catch (Exception ve)
            {
                return new Tuple<Connection, string>(null, "無法連線至『" + AccessPoint + "』主機" + System.Environment.NewLine + "訊息:『" + ve.Message + "』");
            }
        }
 private Connection GetPooldConncetion()
 {
     Connection result = null;
     lock ((idle as ICollection).SyncRoot)
     {
         if (idle.Count>0)
             result = idle.Pop();
         if (result!=null && (int)(DateTime.Now - result.LastUseTime).TotalSeconds > FDFSConfig.Connection_LifeTime)
         {
             foreach (Connection conn in idle)
             {
                 conn.Close();
             }
             idle = new Stack<Connection>(maxConnection);
             result = null;
         }
     }
     lock ((inUse as ICollection).SyncRoot)
     {
         if (inUse.Count == maxConnection)
             return null;                    
         if (result == null)
         {
             result = new Connection();
             result.Connect(endPoint);
             result.Pool = this;
         }
         inUse.Add(result);
     }
     return result;
 }
Example #8
0
    /** A simple test case. Invoke with a number of group names.
     * Each member will cast the group name every second.
     */
    public static void Main(string[] args)
    {
        int i;
        ParseCmdLine (args);
        conn = new Connection ();
        conn.Connect();

        // Create an initial set of endpoints
        memb_a = new Member[nmembers];
        for(i=0; i<nmembers; i++)
            CreateEndpt (i);

        // The main loop
        while(true) {
            // While there are pending messages --- read them
            while (conn.Poll ()) {
                Message msg = conn.Recv ();
                HandleMsg(msg);
                Console.Out.Flush();
            }

            // Sleep for a while
            Thread.Sleep(sleep_timeout);

            // Generate some random actions, one for each member.
            for (i=0; i<nmembers; i++)
                RandAction(i);
        }
    }
 internal Connection TryConnect()
 {
     Connection connection = new Connection();
     connection.EnableSession = false;
     connection.EnableSecureTunnel = true;
     connection.Connect(AccessPoint, ContractName, User, Password);
     return connection;
 }
Example #10
0
 public void Register(UserMOD userMOD)
 {
     using (_conn = new Connection<UserMOD>())
     {
         _conn.Connect("mongodb://localhost", "napegada", "user")
              .Insert(userMOD);
     }
 }
Example #11
0
 public UserMOD GetByMail(string mail)
 {
     using (_conn = new Connection<UserMOD>())
     {
         return _conn.Connect("mongodb://localhost", "napegada", "user")
                     .FindOne(Query.EQ("Mail", mail));
     }
 }
Example #12
0
 public UserMOD GetById(ObjectId id)
 {
     using (_conn = new Connection<UserMOD>())
     {
         return _conn.Connect("mongodb://localhost", "napegada", "user")
                     .FindOne(Query.EQ("_id", id));
     }
 }
Example #13
0
        protected Connection GetConnection()
        {
            // Open database connection
            string dsn = "Server=127.0.0.1;Port=3306;Initial Catalog=test;User Id=root;Password=;CharSet=utf8;Allow User Variables=True";

            Connection db = new Connection();
            db.Connect(dsn);
            return db;
        }
Example #14
0
 public bool IsUser(UserMOD userMOD)
 {
     using (_conn = new Connection<UserMOD>())
     {
         return _conn.Connect("mongodb://localhost", "napegada", "user")
                 .AsQueryable<UserMOD>()
                 .Any(u => u.Mail.Equals(userMOD.Mail) && u.Password.Equals(userMOD.Password));
     }
 }
Example #15
0
    public void Assemble(BaseTool thisTool)
    {
        var thisObject = thisTool.gameObject;

        GetAllConnections();
        var        toolConnections = thisTool.GetConnections();
        Connection nearConnection = null, desiredConnection = null;

        float dist = 1000;

        foreach (var myConn in toolConnections)
        {
            if (myConn.IsConnected)
            {
                continue;
            }

            foreach (var othersConn in _allConnections)
            {
                if (othersConn.IsConnected)
                {
                    continue;
                }

                var currDist = Vector3.Distance(myConn.transform.position, othersConn.transform.position);
                if ((!(currDist < dist)) ||
                    (othersConn.GetComponentInParent <BaseTool>() == thisTool))
                {
                    continue;
                }

                nearConnection    = othersConn;
                desiredConnection = myConn;
                dist = currDist;
            }
        }

        if (nearConnection != null)
        {
            var emptyGo = new GameObject();
            _refTransform          = emptyGo.transform;
            _refTransform.position = nearConnection.transform.position;
            _refTransform.rotation = nearConnection.transform.rotation;
            _refTransform.Rotate(180f, 0f, 0f);

            var localPos = desiredConnection.transform.localPosition;

            var newConnRot = _refTransform.rotation * Quaternion.Inverse(desiredConnection.transform.rotation);
            thisObject.transform.rotation *= newConnRot;
            thisObject.transform.position  = _refTransform.position;
            thisObject.transform.Translate(-localPos);
            Destroy(emptyGo);
        }

        desiredConnection?.Connect(nearConnection);
    }
Example #16
0
 public void Update(UserMOD userMOD, ObjectId id)
 {
     using (_conn = new Connection<UserMOD>())
     {
         _conn.Connect("mongodb://localhost", "napegada", "user")
              .Update(Query<UserMOD>.EQ(u => u.Id, id), Update<UserMOD>.Set(u => u.NameFile, userMOD.NameFile)
                                                                        .Set(u => u.Password, userMOD.Password)
                                                                        .Set(u => u.Name, userMOD.Name));
     }
 }
 protected override void OnInitializeAsync()
 {
     try
     {
         Conn = new Connection();
         Conn.Connect(LogApplication, LogContract, "logquery", "logquery1234");
     }
     catch (Exception ex)
     {
         RTOut.WriteError(ex);
     }
 }
Example #18
0
        public Connection Checkout()
        {
            lock (_ConnectionQueue)
            {
                if (_ConnectionQueue.Count > 0)
                    return _ConnectionQueue.Dequeue();
            }

            //TODO: Come back and put support to ensure that we do not create a fuckton of connections. 
            Connection connection = new Connection(_Uri, _Config);
            connection.Connect();
            return connection;
        }
Example #19
0
    public static void Main(string[] args)
    {
        conn = new Connection ();
        conn.Connect();

        JoinOps jops = new JoinOps();
        jops.group_name = "CS_Mtalk" ;

        // Create the endpoint
        memb = new Member(conn);

        memb.Join(jops);
        MainLoop();
    }
Example #20
0
        public void Connect(string host, int port, string botnickname, string serverpassword)
        {
            //Create Identd server
            Identd.Start(botnickname);

            //Create connection args
            ircArgs = new ConnectionArgs();
            ircArgs.Hostname = host;
            ircArgs.Port = port;
            ircArgs.ClientName = "TWITCHCLIENT 3"; //yay, twitchclient 3 is out!
            ircArgs.Nick = botnickname;
            ircArgs.RealName = botnickname;
            ircArgs.UserName = botnickname;
            ircArgs.ServerPassword = serverpassword;

            //Create ircConnection
            ircConnection = new Connection(ircArgs, false, false);

            //Setup our irc event handlers
            ircConnection.Listener.OnRegistered += new RegisteredEventHandler(OnRegistered);
            ircConnection.Listener.OnPublic += new PublicMessageEventHandler(OnPublic);
            ircConnection.Listener.OnPrivate += new PrivateMessageEventHandler(OnPrivate);
            ircConnection.Listener.OnChannelModeChange += new ChannelModeChangeEventHandler(OnChannelModeChange);
            ircConnection.Listener.OnError += new ErrorMessageEventHandler(OnError);
            ircConnection.Listener.OnDisconnected += new DisconnectedEventHandler(OnDisconnected);
            ircConnection.Listener.OnAction += new ActionEventHandler(OnAction);

            //Let's try connecting!
            try
            {
                Logger.Log.Write("Connecting to " + host + ":" + port + "...", ConsoleColor.DarkGray);
                ircConnection.Connect();
            }
            catch (Exception e)
            {
                Logger.Log.Write("Error connecting to network, exception: " + e.ToString(), ConsoleColor.Red);
                Identd.Stop();
                return;
            }

            //We made it!
            Logger.Log.Write("Connected to " + host, ConsoleColor.DarkGray);

            //Create our message queue poller
            messageQueue = new Queue<KeyValuePair<Channel, string>>();
            previousMessageTimestamps = new List<int>();
            messageThread = new Thread(new ThreadStart(MessagePoller));
            messageThread.Start();
        }
Example #21
0
    /** A simple test case. Invoke with a number of group names.
     * Each member will cast the group name every second.
     */
    public static void Main(string[] args)
    {
        ParseCmdLine (args);
        conn = new Connection ();
        conn.Connect();

        JoinOps jops = new JoinOps();
        jops.group_name = "CS_Perf" ;

        // Create the endpoint
        memb = new Member(conn);

        if (prog == "rpc")
            RpcMainLoop(jops);
        else
            ThrouMainLoop(jops);
    }
Example #22
0
 public void Connect()
 {
     Identd.Start(_settings.Nick);
     var connectionArgs = new ConnectionArgs(_settings.Nick, _settings.Server);
     _connection = new Connection(connectionArgs, DISABLE_CTCP, DISABLE_DCC);
     InitializeEvents();
     try
     {
         Console.WriteLine("* Connecting to {0} as {1}", _settings.Server, _settings.Nick);
         _connection.Connect();
     }
     catch
     {
         Identd.Stop();
         throw;
     }
 }
        private void buttonX1_Click(object sender, EventArgs e)
        {
            //FISCA.Authentication.DSAServices.p

            Connection con = new Connection();

            //取得局端登入後Greening發的Passport,並登入指定的Contract
            con.Connect(FISCA.Authentication.DSAServices.DefaultDataSource.AccessPoint, "ischool.kh.central_office.user", FISCA.Authentication.DSAServices.PassportToken);

            //取得該Contract所發的Passport
            Envelope Response = con.SendRequest("DS.Base.GetPassportToken", new Envelope());
            PassportToken Passport = new PassportToken(Response.Body);

            //TODO:拿此Passport登入各校
            Connection conSchool = new Connection();
            conSchool.Connect("dev.jh_kh", "ischool.kh.central_office", Passport);
        }
 private void FrmApproach_Import_Load(object sender, EventArgs e)
 {
     Connection conn = new Connection();
     try
     {
         conn.EnableSession = false;
         conn.Connect(
             "j.kh.edu.tw",
             "centraloffice",
             FISCA.Authentication.DSAServices.AccessPoint,
             FISCA.Authentication.DSAServices.AccessPoint
         );
     }
     catch (Exception ex)
     {
         this.lblMessage.Text = ex.Message;
         return;
     }
     //var result = ContractService.GetOpenDate(Connection); FISCA.Authentication.DSAServices.AccessPoint
     //< data >
     //  < uid > 7448 </ uid >
     //  < last_update > 2015 - 07 - 09 17:57:22.974804 </ last_update >
     //  < school_year > 103 </ school_year >
     //  < start_date > 2015 - 07 - 01 00:00:00 </ start_date >
     //  < end_date > 2015 - 07 - 31 00:00:00 </ end_date >
     //</ data >
     //result.Element("school_year").Value;
     XElement result;
     try
     {
         result = ContractService.GetOpenDate(conn);
     }
     catch(Exception ex)
     {
         this.lblMessage.Text = ex.Message;
         return;
     }
     this.SchoolYear = int.Parse(result.Element("school_year").Value);
     this.StartDate = DateTime.Parse(result.Element("start_date").Value);
     this.EndDate = DateTime.Parse(result.Element("end_date").Value);
     this.lblMessage.Text = string.Format("目前填報年度:{0}\n填報期間:{1}~{2}", this.SchoolYear, this.StartDate.ToShortDateString(),this.EndDate.ToShortDateString());
     this.btnNext.Visible = true;
 }
        internal SecurityToken GetSecurityToken()
        {
            if (!chkPassport.Checked)
            {
                return new BasicSecurityToken(txtUser.Text, txtPwd.Text);
            }
            else
            {
                Connection greenCon = new Connection();
                greenCon.EnableSecureTunnel = true;
                greenCon.EnableSession = true;
                greenCon.Connect(txtProvider.Text, string.Empty, txtUser.Text.Trim(), txtPwd.Text);

                Envelope rsp = greenCon.SendRequest("DS.Base.GetPassportToken", new Envelope());
                txtPassport.Text = rsp.Body.XmlString;
                xmlSyntaxLanguage1.FormatDocument(txtPassport.Document);
                PassportSecurityToken stt = new PassportSecurityToken(rsp.Body.XmlString);
                return stt;
            }
        }
Example #26
0
    static void Main(string[] args)
    {
        using (Connection conn = new Connection("TMC"))
        {
            // Connect to local server
            conn.Connect("192.168.1.104");

            // Create a new point
            DBObject point = conn.CreateObject("CPointAlgManual", ObjectId.Root, "My Point");

            // Set a property
            point["FullScale"] = 200;

            // Get a property
            Console.WriteLine("FullScale = {0}", point["FullScale"]);

            while (true)
            {

            }
        }
    }
Example #27
0
        public string Create(Sala sala)
        {
            SqlCommand.CommandText = @"Insert into Salas(nomeDaSala) values ('" + sala.sala + "');" +
                                     "Create table " + sala.sala + " (" +
                                     "ID smallint primary key identity," +
                                     "Alunos varchar(100) )" +
                                     "Create table " + sala.sala + "SegundaEtapa (" +
                                     "ID smallint primary key identity," +
                                     "Alunos varchar(100) )";
            try
            {
                SqlCommand.Connection = Connection.Connect();
                SqlCommand.ExecuteNonQuery();
                Connection.Disconnect();

                Message = "cadastrado com sucesso.";
            }
            catch (Exception ex)
            {
                Message = "erro no banco de dados.";
            }

            return(Message);
        }
Example #28
0
        static void Main(string[] args)
        {
            myList <byte> msgs;
            string        strmsg;
            Connection    cc = new Connection();

            cc.Connect();
            Connection sc = new Connection("chat.facebook.com");

            sc.Connect();
            while (true)
            {
                strmsg = "";
                msgs   = cc.GetMessages();
                if ((msgs != null) && (msgs.Count > 0))
                {
                    strmsg = ConvertMsgToString(msgs);
                    sc.Send(msgs);
                }
                msgs = sc.GetMessages();
                if ((msgs != null) && (msgs.Count > 0))
                {
                    strmsg = ConvertMsgToString(msgs);
                    cc.Send(msgs);
                }
                if (strmsg.Length > 0)
                {
                    Console.WriteLine(strmsg);
                }
                if (strmsg.Contains("proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
                {
                    cc.StartTls();
                    sc.StartTls();
                }
            }
        }
Example #29
0
        protected override void Start()
        {
            if (Mst.Client.Rooms.ForceClientMode)
            {
                return;
            }

            // Set room oprions
            roomOptions = SetRoomOptions();

            // Set port of the Mirror server
            SetPort(roomOptions.RoomPort);

            // Add master server connection and disconnection listeners
            Connection.AddConnectionListener(OnConnectedToMasterServerEventHandler, true);
            Connection.AddDisconnectionListener(OnDisconnectedFromMasterServerEventHandler, false);

            // If connection to master server is not established
            if (!Connection.IsConnected && !Connection.IsConnecting)
            {
                Connection.UseSsl = MstApplicationConfig.Instance.UseSecure || Mst.Args.UseSecure;
                Connection.Connect(masterIp, masterPort);
            }
        }
Example #30
0
        protected override void OnInitialize()
        {
            // Get mirror network manager
            MirrorNetworkManager = NetworkManager.singleton;

            // If we hav offline scene in global options
            if (Mst.Options.Has(MstDictKeys.ROOM_OFFLINE_SCENE_NAME))
            {
                logger.Debug("Assigning offline scene to mirror network manager");
                MirrorNetworkManager.offlineScene = Mst.Options.AsString(MstDictKeys.ROOM_OFFLINE_SCENE_NAME);
            }

            // Start listening to OnServerStartedEvent of our MirrorNetworkManager
            if (NetworkManager.singleton is RoomNetworkManager manager)
            {
                manager.OnClientStartedEvent += OnMirrorClientStartedEventHandler;
                manager.OnClientStoppedEvent += OnMirrorClientStoppedEventHandler;
            }
            else
            {
                logger.Error("Before using MirrorNetworkManager add it to scene");
            }

            // Add master server connection and disconnection listeners
            Connection.AddDisconnectionListener(OnDisconnectedFromMasterServerEventHandler, false);

            MstTimer.WaitForSeconds(0.5f, () =>
            {
                // If connection to master server is not established
                if (!Connection.IsConnected && !Connection.IsConnecting)
                {
                    Connection.UseSsl = MstApplicationConfig.Instance.UseSecure;
                    Connection.Connect(masterIp, masterPort);
                }
            });
        }
Example #31
0
 public ActionResult Display(string ip, int port)
 {
     try
     {
         // try to parse the ip, if it fails goto different action.
         IPAddress.Parse(ip);
         Connection c = Connection.Instance;
         // disconnect if connected
         if (c.IsConnected || c.IsWaiting)
         {
             c.CloseConnection();
         }
         c.Connect(ip, port);
         c.ReadData();
         Location location = c.GetLocation;
         UpdateSessionDisplay(location.Lon, location.Lat);
         Session["stop"] = 1;
         return(View());
     }
     catch
     {
         return(RedirectToAction("LoadAndDisplay", new { fileName = ip, refreshRate = port }));
     }
 }
Example #32
0
        static void Main(string[] args)
        {
            UserControl usercontrol = new UserControl();
            bool        isExit      = false;
            string      input;

            Instruction();
            while (!isExit)
            {
                input = Console.ReadLine();
                Enum.TryParse(input, true, out usercontrol);
                switch (usercontrol)
                {
                case UserControl.Exercise1:
                    Console.WriteLine("Solve of {0}", UserControl.Exercise1);
                    Exercise1 exercise1 = new Exercise1();
                    exercise1.Show();
                    Connection myConnection = new Connection();
                    Display    myDisplay    = new Display();
                    myConnection.MessageArrived += new MessageHandler(myDisplay.DisplayMessage);
                    myConnection.Connect();
                    Console.ReadKey();
                    break;

                case UserControl.Exercise2:
                    Console.WriteLine("Solve of {0}", UserControl.Exercise2);
                    Exercise2 exercise2 = new Exercise2();
                    exercise2.Show();
                    break;

                case UserControl.Exit: isExit = true; break;

                default: Instruction(); break;
                }
            }
        }
Example #33
0
        public bool AuthenticateUser()
        {
            string     storedProcedure = "Gen_AuthenticateUser";
            Connection connection      = new Connection();
            SqlCommand sqlCommand      = new SqlCommand();

            sqlCommand.CommandText = storedProcedure;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Connection  = connection.connectionString;

            SqlParameter paramIdUsuario = new SqlParameter();

            paramIdUsuario.SqlDbType     = SqlDbType.NVarChar;
            paramIdUsuario.ParameterName = "@IdUsuario";
            paramIdUsuario.Value         = IdUsuario;
            sqlCommand.Parameters.Add(paramIdUsuario);

            SqlParameter paramContrasenia = new SqlParameter();

            paramContrasenia.SqlDbType     = SqlDbType.NVarChar;
            paramContrasenia.ParameterName = "@Contrasenia";
            paramContrasenia.Value         = Contrasenia;
            sqlCommand.Parameters.Add(paramContrasenia);

            SqlParameter paramComprobacion = new SqlParameter();

            paramComprobacion.Direction     = ParameterDirection.Output;
            paramComprobacion.SqlDbType     = SqlDbType.Bit;
            paramComprobacion.ParameterName = "@Validation";
            sqlCommand.Parameters.Add(paramComprobacion);

            connection.Connect();
            sqlCommand.ExecuteNonQuery();
            connection.Disconnect();
            return(bool.Parse(sqlCommand.Parameters["@Validation"].Value.ToString()));
        }
Example #34
0
        public Usuarios Read(string idUsuario)
        {
            Usuarios   usuarios        = new Usuarios();
            string     storedProcedure = "Negocio_GetData_User";
            Connection connection      = new Connection();
            SqlCommand sqlCommand      = new SqlCommand();

            sqlCommand.CommandText = storedProcedure;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Connection  = connection.connectionString;

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

            SqlParameter parameter = new SqlParameter();

            parameter.SqlDbType     = SqlDbType.NVarChar;
            parameter.ParameterName = "@IdUsuario";
            parameter.Value         = idUsuario;
            sqlCommand.Parameters.Add(parameter);

            connection.Connect();

            using (SqlDataReader reader = sqlCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    usuarios.IdUsuario        = reader["IdUsuario"].ToString();
                    usuarios.Nombres          = reader["Nombres"].ToString();
                    usuarios.Apellidos        = reader["Apellidos"].ToString();
                    usuarios.NumeroTelefonico = reader["NumeroTelefonico"].ToString();
                }
            }

            connection.Disconnect();
            return(usuarios);
        }
        public override void HandleReceive(byte[] receiveBuffer, int offset, int count)
        {
            byte[] requestASCII = new byte[count];
            Array.ConstrainedCopy(receiveBuffer, offset, requestASCII, 0, count);
            Console.WriteLine("Socks request received: {0}\r\n{1}", Encoding.ASCII.GetString(requestASCII), Log.ByteArrayToHexString(requestASCII));

            Socks4Request request = Socks4Request.Parse(receiveBuffer);

            if (request == null)
            {
                Console.WriteLine("Could not parse socks request");
                SocksCommon.SendSocksError(_Client);
                return;
            }

            Connection requestedConnection = null;

            try
            {
                requestedConnection = Connection.Connect(request.RemoteHostIP, request.RemotePort);
                Console.WriteLine("{0} --> Socks Request successful, connected to {1}:{2}", _Client, request.RemoteHostIP, request.RemotePort);
            }
            catch
            {
                SocksCommon.SendSocksError(_Client);
                return;
            }

            requestedConnection.SetObserver(new TransmissionRedirectConnectionObserver(_Client, false));
            _Client.SetObserver(new TransmissionRedirectConnectionObserver(requestedConnection, true));

            // _Client will continue to receive, but destination needs to start receiveing.
            requestedConnection.BeginReceiving();

            SocksCommon.SendSocksSuccess(_Client, request.RemotePort, request.RemoteHostIP);
        }
Example #36
0
        public void store_and_delete_a_forum()
        {
            Connection one = new Connection();
            Connection two = new Connection();

            ForumRepo repo = new ForumRepo(new Connection());

            //Create forum

            ForumModel forum = new ForumModel();

            forum.name        = "testname";
            forum.description = "testdescription";

            int id = repo.store(forum);


            one.Connect();
            SqlCommand    sqlCommand = new SqlCommand("select * from forum where name = 'testname' and description ='testdescription'", one.getConnection());
            SqlDataReader reader     = sqlCommand.ExecuteReader();

            Assert.AreEqual(true, reader.HasRows);
            one.disConnect();

            repo.destroy(id);

            two.Connect();

            //Delete forum

            SqlCommand    sqlCommandTwo = new SqlCommand("select * from forum where name = 'testname' and description ='testdescription'", two.getConnection());
            SqlDataReader readerTwo     = sqlCommandTwo.ExecuteReader();

            Assert.AreEqual(false, readerTwo.HasRows);
            one.disConnect();
        }
Example #37
0
        public bool UpdateNode() // Corregir
        {
            string     storedProcedure = "Negocio_Create_Node";
            Connection connection      = new Connection();
            SqlCommand sqlCommand      = new SqlCommand();

            sqlCommand.CommandText = storedProcedure;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Connection  = connection.connectionString;

            SqlParameter paramIdCategoria = new SqlParameter();

            paramIdCategoria.SqlDbType     = SqlDbType.NVarChar;
            paramIdCategoria.ParameterName = "@IdCategoria";
            paramIdCategoria.Value         = IdCategoria;
            sqlCommand.Parameters.Add(paramIdCategoria);

            SqlParameter paramIdUsuario = new SqlParameter();

            paramIdUsuario.SqlDbType     = SqlDbType.NVarChar;
            paramIdUsuario.ParameterName = "@IdUsuario";
            paramIdUsuario.Value         = IdUsuario;
            sqlCommand.Parameters.Add(paramIdUsuario);

            SqlParameter paramComprobacion = new SqlParameter();

            paramComprobacion.Direction     = ParameterDirection.Output;
            paramComprobacion.SqlDbType     = SqlDbType.Bit;
            paramComprobacion.ParameterName = "@Validation";
            sqlCommand.Parameters.Add(paramComprobacion);

            connection.Connect();
            sqlCommand.ExecuteNonQuery();
            connection.Disconnect();
            return(bool.Parse(sqlCommand.Parameters["@Validation"].Value.ToString()));
        }
Example #38
0
        static void Main(string[] args)
        {
            WriteLine("1. Factory Method");

            string pattern = ReadLine();

            switch (pattern)
            {
            case FactoryMethod:
                Connection connection1 = FactoryConnection.GetConnection("ORACLE");
                WriteLine(connection1.Connect());
                WriteLine(connection1.Disconnect());

                Connection connection2 = FactoryConnection.GetConnection("SQL");
                WriteLine(connection2.Connect());
                WriteLine(connection2.Disconnect());

                break;

            default:
                WriteLine("Pattern not implemented");
                return;
            }
        }
Example #39
0
        public override void HandleConnectionRequest(Connection acceptedConnection)
        {
            Connection redirectConnection = null;

            try
            {
                redirectConnection = Connection.Connect(_RedirectHost, _RedirectPort);
                Console.WriteLine("Connected to Port Redirection Target {0}:{1}", _RedirectHost, _RedirectPort);
            }
            catch (Exception exp)
            {
                Console.WriteLine("Could Not Connect to Port Redirection Target {0}:{1}. Reason: {2}", _RedirectHost, _RedirectPort, exp);
                acceptedConnection.Close();
                return;
            }

            acceptedConnection.SetObserver(new TransmissionRedirectConnectionObserver(redirectConnection, true));
            redirectConnection.SetObserver(new TransmissionRedirectConnectionObserver(acceptedConnection, false));

            acceptedConnection.IsBeingTraced = ObservedServer.IsBeingTraced;

            acceptedConnection.BeginReceiving();
            redirectConnection.BeginReceiving();
        }
Example #40
0
    /** A simple test case. Invoke with a number of group names.
     * Each member will cast the group name every second.
     */
    public static void Main(string[] args)
    {
        int i;

        ParseCmdLine(args);
        conn = new Connection();
        conn.Connect();

        // Create an initial set of endpoints
        memb_a = new Member[nmembers];
        for (i = 0; i < nmembers; i++)
        {
            CreateEndpt(i);
        }

        // The main loop
        while (true)
        {
            // While there are pending messages --- read them
            while (conn.Poll())
            {
                Message msg = conn.Recv();
                HandleMsg(msg);
                Console.Out.Flush();
            }

            // Sleep for a while
            Thread.Sleep(sleep_timeout);

            // Generate some random actions, one for each member.
            for (i = 0; i < nmembers; i++)
            {
                RandAction(i);
            }
        }
    }
        public int GetRobots()
        {
            Connection connection = new Connection(true);

            for (int i = 0; connection.Connect("localhost", 13000 + i, true); i++)
            {
                Console.WriteLine("Connection etablished to Moda Server , on port : " + (13000 + i));
                RobotPHX robotPHX = connection.QueryRobotPHX("/blli");
                if (robotPHX != null)
                {
                    Robot robot = new Robot(robotPHX, "p0");
                    mutex.WaitOne();
                    availableRobot.Push(robot);
                    listRobot.Add(robot);
                    mutex.ReleaseMutex();
                }
                else
                {
                    Console.WriteLine("Error while retreiving robot, skipping");
                }
                connection = new Connection(true);
            }
            return(listRobot.Count);
        }
Example #42
0
        protected override void OnInitialize()
        {
            if (Mst.Client.Rooms.ForceClientMode)
            {
                return;
            }

            // Start listening to OnServerStartedEvent of our MirrorNetworkManager
            if (RoomNetworkManager is RoomNetworkManager manager)
            {
                manager.OnServerStartedEvent      += OnMirrorServerStartedEventHandler;
                manager.OnClientDisconnectedEvent += OnMirrorClientDisconnectedEvent;
                manager.OnServerStoppedEvent      += OnMirrorServerStoppedEventHandler;
            }
            else
            {
                logger.Error("We cannot register listeners of MirrorNetworkManager events because we cannot find it onscene");
            }

            // Set room oprions
            roomOptions = SetRoomOptions();

            // Set port of the Mirror server
            SetPort(roomOptions.RoomPort);

            // Add master server connection and disconnection listeners
            Connection.AddConnectionListener(OnConnectedToMasterServerEventHandler, true);
            Connection.AddDisconnectionListener(OnDisconnectedFromMasterServerEventHandler, false);

            // If connection to master server is not established
            if (!Connection.IsConnected && !Connection.IsConnecting)
            {
                Connection.UseSsl = MstApplicationConfig.Instance.UseSecure;
                Connection.Connect(masterIp, masterPort);
            }
        }
Example #43
0
        public void Start(bool useUsb, Action<string> consoleCallback)
        {
            string serial = ""; // Only when using USB do you need an actual 'serial' name.
            int ret;

            if (useUsb || !string.IsNullOrEmpty(package))
            {
                Console.WriteLine("Waiting for Vita to connect...");
                ScePsmDevice? vita = null;
                for (; ; )
                {
                    ScePsmDevice[] deviceArray;
                    PSMFunctions.ListDevices(out deviceArray);
                    foreach (ScePsmDevice dev in deviceArray)
                    {
                        if (dev.online > 0)
                        {
                            vita = dev;
                            break;
                        }
                    }
                    if (vita != null)
                    {
                        break;
                    }
                }
                Guid devId = vita.Value.guid;
                serial = new string(vita.Value.deviceID, 0, 17);
                Console.WriteLine("Found Vita {0}, serial: {1}", devId, serial);
                if ((ret = PSMFunctions.Connect(devId)) < 0)
                {
                    Console.WriteLine("Error connecting to Vita: 0x{0:X}", ret);
                    throw new IOException("Cannot connect to Vita.");
                }
                this.handle = devId;

                // request version or other calls will fail
            #if USE_UNITY
                string devagentver = null;
                string hosttransportver = null;
                if ((ret = PSMFunctions.GetAgentVersion(this.handle, ref devagentver, ref hosttransportver)) != 0)
                {
                    Console.WriteLine("Error getting version: 0x{0:X}", ret);
                    throw new IOException("Cannot connect to Vita.");
                }
                Console.WriteLine("Connected agent version: {0}, transport version: {1}", devagentver, hosttransportver);
            #else
            PSMFunctions.Version(this.handle);
            #endif

            #if USE_APP_KEY
            byte[] buffer = File.ReadAllBytes("kdev.p12");

            if ((ret = PSMFunctions.ExistAppExeKey(this.handle, DRMFunctions.ReadAccountIdFromKdevP12(buffer), "*", "np")) != 1)
            {
                Console.WriteLine("Setting app key to: {0}", appkeypath);
                if ((ret = PSMFunctions.SetAppExeKey(this.handle, appkeypath)) != 0)
                {
                    Console.WriteLine("Error setting key: 0x{0:X}", ret);
                    throw new IOException("Cannot set app key.");
                }
            }
            #endif
            }

            if (!string.IsNullOrEmpty(package))
            {
                Console.WriteLine("Installing package {0} as {1}.", package, name);
                if ((ret = PSMFunctions.Install(this.handle, package, name)) != 0)
                {
                    Console.WriteLine("Error installing package: 0x{0:X}", ret);
                    throw new IOException("Cannot connect to Vita.");
                }

                Console.WriteLine("Successfully installed package.");

                Thread.Sleep(500);

            #if !USE_ANDROID
                if (Program.exitAfterInstall)
                {
                    Environment.Exit(0);
                }
            #endif
            }

            if (useUsb)
            {
                callback = new PsmDeviceConsoleCallback(consoleCallback);
                Console.WriteLine("Setting console callback.");
                PSMFunctions.SetConsoleWrite(this.handle, Marshal.GetFunctionPointerForDelegate(callback));

                Console.WriteLine("Launching {0}.", name);
            #if USE_UNITY
                if ((ret = PSMFunctions.LaunchUnity(this.handle, name, 0, new string[] { })) != 0)
                {
                    Console.WriteLine("Error running application: 0x{0:X}", ret);
                    throw new IOException("Cannot connect to Vita.");
                }
            #else
            if ((ret = PSMFunctions.Launch(this.handle, name, true, false, false, false, "")) != 0)
            {
                Console.WriteLine("Error running application: 0x{0:X}", ret);
                throw new IOException("Cannot connect to Vita.");
            }
            #endif
            }

            Console.WriteLine("Connecting debugger.");
            conn = getconn(serial);
            conn.EventHandler = new ConnEventHandler();
            conn.ErrorHandler += HandleConnErrorHandler;
            conn.Connect(out reciever);

            Console.WriteLine("Waiting for app to start up...");
            #if !USE_UNITY
            conn.VM_Resume();
            #endif
            Thread.Sleep(2000);
            Console.WriteLine("Getting variables.");
            rootdomain = conn.RootDomain;
            corlibid = conn.Domain_GetCorlib(rootdomain);
            assid = conn.Domain_GetEntryAssembly(rootdomain);
            foreach (long thread in conn.VM_GetThreads())
            {
                if (conn.Thread_GetName(thread) == "")
                {
                    threadid = thread;
                }
            }
            //Console.WriteLine ("Root Domain: {0}\nCorlib: {1}\nExeAssembly: {2}\nThread: {3}", rootdomain, corlibid, assid, threadid);
            Console.WriteLine("Ready for hacking.");
        }
Example #44
0
    /// <summary>
    /// Adds a building to the global building pool.
    /// </summary>
    /// <returns>
    /// A pointer to the newly created building.
    /// </returns>
    /// <param name='newBuilding'>
    /// The new building to add to the global pool.
    /// </param>
    public bool AddBuilding(BaseBuilding newBuilding)
    {
        m_CurrBuilding = null;
        bool buildingIsNew = false;

        if(m_TotalBuildings.Count - m_PowerNodes.Count >= MAX_BUILDINGS)
            return false;

        int buildingPrice = Globals.WorldView.ResManager.ConsumeResources(newBuilding.MineralPrice);
        if(buildingPrice < newBuilding.MineralPrice)
        {
            Globals.WorldView.OverlayView.PushMessage(Color.green, "Not enough funds!");
            Globals.WorldView.ResManager.AddResources(buildingPrice);
            return false;
        }

        Globals.WorldView.OverlayView.PushMessage(Color.green, "Placed new building: " + newBuilding.Name);

        // temporarily color the sprite white (it's normal color)
        //newBuilding.Sprite.SetColor(Color.white);
        newBuilding.IsConstructing = true;
        newBuilding.CurrConstructTime = 0.0f;

        if(newBuilding is CommandCenterBuilding)
        {
            CommandCenterBuilding newCC = (CommandCenterBuilding)newBuilding;

            if(!m_CommandCenters.Contains(newCC))
            {
                m_PowerNodes.Add(newCC);
                m_CommandCenters.Add(newCC);
                buildingIsNew = true;
            }
        }
        else if(newBuilding is PowerNodeBuilding)
        {
            PowerNodeBuilding powerNode = (PowerNodeBuilding)newBuilding;

            if(!m_PowerNodes.Contains(powerNode))
            {
                m_PowerNodes.Add(powerNode);
                buildingIsNew = true;
            }
        }
        else
        {
            // grey the sprite out and let the manager check
            // to see that it's powered
            newBuilding.Sprite.SetColor(Color.grey);
            if(!m_WorldBuildings.Contains(newBuilding))
            {
                m_WorldBuildings.Add(newBuilding);
                buildingIsNew = true;
            }
        }

        if(buildingIsNew)
        {
            m_TotalBuildings.Add(newBuilding);

            if(m_ClosestBuildings != null)
            {
                bool addedToNeighbor = false;
                bool isPowerNode = newBuilding is PowerNodeBuilding;

                foreach(BaseBuilding neighbor in m_ClosestBuildings)
                {
                    if(isPowerNode && !(neighbor is PowerNodeBuilding))
                        addedToNeighbor = newBuilding.AddNeighbor(neighbor);
                    else
                        addedToNeighbor = neighbor.AddNeighbor(newBuilding);

                    if(addedToNeighbor)
                    {
                        Connection NewConnection = new Connection(neighbor.Position, newBuilding.Position, 0.0f);
                        m_Connections.Add(NewConnection);
                        NewConnection.Connect();
                    }
                }
            }
            return true;
        }
        else
            return false;
    }
Example #45
0
 private void button1_Click(object sender, EventArgs e)
 {
     Connection.Connect("192.168.1.19");
     SliderApi.SliderOpenWindow();
 }
Example #46
0
        private void Run(string[] args)
        {
            if (args.Length < 1)
            {
                printUsage();
                return;
            }
            cfgFile = new ConfigFile(args[0]);

            Config  connectionConfig;
            Config  programConfig;
            Message heartbeatMessage;
            Field   tempField;
            string  configValue;
            string  tempSubject;
            //Config Variables
            short globalHeartbeatCount = 0;
            short heartbeatHolder      = 0;
            short heartbeatCountdown   = 0;
            short loopCountdown        = 0;
            short updateRate           = 0;

            //Subscription Callback
            LogCallback cb = new LogCallback();

            //Load Config File
            result = cfgFile.Load();
            check("ConfigFileLoad", result);

            //Look up configuration for the middleware
            result = cfgFile.LookupConfig("connection-config", out connectionConfig);
            check("LookUpConfig", result);

            //Create connection from configuration
            result = ConnectionFactory.Create(connectionConfig, out conn);
            check("Creating Connection", result);

            //Connect to the Network
            result = conn.Connect();
            check("Connect", result);

            //Output Info
            Console.Out.WriteLine(ConnectionFactory.GetAPIVersion());
            Console.Out.WriteLine("Middleware version= " + conn.GetLibraryVersion());

            //Lookup additional program configuration info
            result = cfgFile.LookupConfig("program-config", out programConfig);
            check("LookUpConfig", result);

            //Set Program Config Values
            result = programConfig.GetValue("update-rate", out configValue);
            check("GetValue", result);
            updateRate = Convert.ToInt16(configValue);
            result     = programConfig.GetValue("loop-time", out configValue);
            check("GetValue", result);
            loopCountdown = Convert.ToInt16(configValue);

            //Create Subscriptions from subscriptions in configFile
            result = cfgFile.LookupSubscription("RECEIVE-LOG", out tempSubject);
            check("LookUpSubscription", result);
            result = conn.Subscribe(tempSubject, cb);
            check("Subscribe", result);

            result = cfgFile.LookupSubscription("SEND-LOG", out tempSubject);
            check("LookUpSubscription", result);
            result = conn.Subscribe(tempSubject, cb);
            check("Subscribe", result);

            //Create a generic message container for the heartbeat message
            result = conn.CreateMessage(out heartbeatMessage);
            check("CreateMessage", result);

            //Load Heartbeat Definition
            result = cfgFile.LookupMessage("C2CX-HEARTBEAT-REC", heartbeatMessage);
            check("LookUpMessage", result);

            //Obtain publish rate field from heartbeat message
            result = heartbeatMessage.GetField("PUB-RATE", out tempField);
            if (!result.IsError())
            {
                result = tempField.GetValue(out heartbeatHolder);
                check("GetValue", result);
            }
            else
            {
                //Default Value
                heartbeatHolder = 30;
            }

            //Ouput some Program Info
            Console.Out.WriteLine("Publishing for " + loopCountdown + " seconds.");
            Console.Out.WriteLine("Publishing Heartbeat Messages every " + heartbeatHolder
                                  + " seconds.");

            result = conn.StartAutoDispatch();
            check("Starting AutoDispatch", result);
            Console.Out.WriteLine("Start Time: " + DateTime.Now.ToString());

            //Publish Loop
            for (; loopCountdown > 0; loopCountdown--)
            {
                //When Countdown reaches 0 publish heartbeat & reset
                if (heartbeatCountdown < 1)
                {
                    globalHeartbeatCount++;

                    //Update Message Counter
                    tempField.SetType(GMSECTypeDefs.I32);
                    tempField.SetName("COUNTER");
                    tempField.SetValue(globalHeartbeatCount);
                    result = heartbeatMessage.AddField(tempField);
                    check("AddField", result);

                    //Publish Heartbeat Message
                    result = conn.Publish(heartbeatMessage);
                    check("Publish", result);

                    //Output Heartbeat marker and reset the counter
                    Console.Out.WriteLine("Published Heartbeat");
                    heartbeatCountdown = heartbeatHolder;
                }
                //Decrement the Counters
                heartbeatCountdown -= updateRate;
                //Sleep for 1 second
                System.Threading.Thread.Sleep(updateRate * 1000);
            }
            //EndTime
            Console.Out.WriteLine("End Time: " + DateTime.Now.ToString());
            result = conn.StopAutoDispatch();
            check("StopAutoDispatch", result);
            result = conn.DestroyMessage(heartbeatMessage);
            check("Destory Message", result);
        }
Example #47
0
        public ExportAcrossClubStudent(string sy, string s)
        {
            Workbook         wb  = new Workbook();
            Exception        exc = null;
            BackgroundWorker bgw = new BackgroundWorker()
            {
                WorkerReportsProgress = true
            };

            bgw.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            {
                MotherForm.SetStatusBarMessage("匯出選社結果(跨部別)", e.ProgressPercentage);
            };
            bgw.DoWork += delegate
            {
                try
                {
                    #region 跨部別
                    {
                        bgw.ReportProgress(1);
                        AccessHelper access = new AccessHelper();
                        loginSchoolList = access.Select <LoginSchool>();
                        //DIC
                        Dictionary <string, OnlineVolunteer> volunteerDic = new Dictionary <string, OnlineVolunteer>();
                        Dictionary <string, OnlineSCJoin>    scjoinDic    = new Dictionary <string, OnlineSCJoin>();
                        Dictionary <string, string>          clubNameDic  = new Dictionary <string, string>();
                        //--
                        wb.Open(new MemoryStream(Properties.Resources.匯出選社結果_跨部別__範本), FileFormatType.Excel2007Xlsx);

                        Worksheet[] ws    = new Worksheet[2];
                        int         sheet = 0;
                        int         p     = 10;
                        foreach (LoginSchool school in loginSchoolList)
                        {
                            p = p + 90 / loginSchoolList.Count;
                            bgw.ReportProgress(p);
                            ws[sheet] = wb.Worksheets[sheet];

                            Connection connection = new Connection();
                            connection.Connect(school.School_Name, "ClubAcrossdivisions", FISCA.Authentication.DSAServices.PassportToken);
                            ws[sheet].Name = school.GetFullName();

                            // 取得社團清單
                            Envelope        rsp      = connection.SendRequest("_.GetClubList", new Envelope(RunService.GetRequest(sy, s)));
                            XDocument       clubDoc  = XDocument.Parse(rsp.Body.XmlString);
                            List <XElement> clubList = clubDoc.Element("Response").Elements("K12.clubrecord.universal").ToList();
                            foreach (XElement club in clubList)
                            {
                                clubNameDic.Add(club.Element("Uid").Value, club.Element("ClubName").Value);
                            }
                            // 取得學生志願序
                            volunteerDic.Clear();
                            rsp = connection.SendRequest("_.GetStudentVolunteer", new Envelope(RunService.GetRequest(sy, s)));
                            XDocument       volunteerDoc = XDocument.Parse(rsp.Body.XmlString);
                            List <XElement> volunteers   = volunteerDoc.Element("Response").Elements("K12.volunteer.universal").ToList();
                            foreach (XElement volunteer in volunteers)
                            {
                                OnlineVolunteer vol = new OnlineVolunteer(volunteer);

                                volunteerDic.Add(vol.RefStudentId, vol);
                            }

                            // 取得學生入選紀錄
                            scjoinDic.Clear();
                            rsp = connection.SendRequest("_.GetStudentSCJoin", new Envelope(RunService.GetRequest(sy, s)));
                            XDocument       scjDoc  = XDocument.Parse(rsp.Body.XmlString);
                            List <XElement> scjoins = scjDoc.Element("Response").Elements("Student").ToList();
                            foreach (XElement scjoin in scjoins)
                            {
                                OnlineSCJoin scj = new OnlineSCJoin(scjoin);
                                scjoinDic.Add(scj.StudentId, scj);
                            }

                            // 讀取志願數上限設定
                            List <ConfigRecord> crList = access.Select <K12.Club.Volunteer.ConfigRecord>();
                            for (int i = 6; i < int.Parse(crList[0].Content) + 6; i++)
                            {
                                ws[sheet].Cells.CopyColumn(ws[sheet].Cells, 4, i);
                                ws[sheet].Cells[0, i].PutValue("志願" + (i - 5));
                            }

                            // 取得所有學生
                            rsp = connection.SendRequest("_.GetAllStudent", new Envelope(RunService.GetRequest(sy, s)));
                            XDocument       allStudentDoc = XDocument.Parse(rsp.Body.XmlString);
                            List <XElement> students      = allStudentDoc.Element("Response").Elements("Student").ToList();

                            int index = 1;
                            foreach (XElement student in students)
                            {
                                if (scjoinDic.ContainsKey(student.Element("Id").Value))
                                {
                                    ws[sheet].Cells.CopyRow(ws[sheet].Cells, 1, index);
                                    ws[sheet].Cells[index, 0].PutValue(student.Element("ClassName").Value);
                                    ws[sheet].Cells[index, 1].PutValue(student.Element("SeatNo").Value);
                                    ws[sheet].Cells[index, 2].PutValue(student.Element("Name").Value);
                                    ws[sheet].Cells[index, 3].PutValue(student.Element("StudentNumber").Value);
                                    ws[sheet].Cells[index, 4].PutValue(scjoinDic[student.Element("Id").Value].ClubName);
                                    ws[sheet].Cells[index, 5].PutValue(scjoinDic[student.Element("Id").Value].IsLock == true ? "是" : "");

                                    List <XElement> club = XDocument.Parse(volunteerDic[student.Element("Id").Value].Content).Element("xml").Elements("Club").ToList();
                                    int             i    = 1;
                                    // 取得志願數設定
                                    int clubCount = int.Parse("" + crList[0].Content);
                                    foreach (XElement clubID in club)
                                    {
                                        ws[sheet].Cells[index, 5 + i].PutValue(clubNameDic[clubID.Attribute("Ref_Club_ID").Value]);
                                        if (i == clubCount)
                                        {
                                            break;
                                        }
                                        i++;
                                    }
                                    index++;
                                }
                            }
                            sheet++;
                        }
                    }
                    #endregion

                    #region
                    {
//                        bgw.ReportProgress(51);
//                        AccessHelper access = new AccessHelper();
//                        List<CLUBRecord> _clubList = access.Select<CLUBRecord>(/*"school_year = "+School.DefaultSchoolYear+" AND semester = "+ School.DefaultSemester*/).ToList();
//                        foreach (CLUBRecord club in _clubList)
//                        {
//                            clubDic.Add(club.UID, club.ClubName);
//                        }
//                        //取得Sheet
//                        Worksheet ws = wb.Worksheets[0];
//                        ws.Name = School.ChineseName;
//                        QueryHelper qh = new QueryHelper();

//                        #region SQL
//                        string selectSQL = string.Format(@"
//SELECT
//	student.id
//    , class.class_name
//    , class.grade_year
//    , seat_no,name
//    , student_number
//    , student.ref_class_id
//    , scjoin.ref_club_id
//    , scjoin.lock
//    , clubrecord.club_name
//    , clubrecord.school_year
//    , clubrecord.semester
//    , volunteer.content
//    , $k12.config.universal.content as wish_limit
//FROM
//    student
//    LEFT OUTER JOIN class on class.id = student.ref_class_id
//    LEFT OUTER JOIN $k12.scjoin.universal AS scjoin
//        ON scjoin.ref_student_id::bigint = student.id
//    LEFT OUTER JOIN $k12.clubrecord.universal AS clubrecord
//        ON clubrecord.uid = scjoin.ref_club_id::bigint
//    LEFT OUTER JOIN $k12.volunteer.universal AS volunteer
//        ON volunteer.ref_student_id::bigint = student.id
//            AND volunteer.school_year = clubrecord.school_year
//            AND volunteer.semester = clubrecord.semester
//    LEFT OUTER JOIN $k12.config.universal ON config_name = '學生選填志願數'
//WHERE
//    student.status in (1, 2)
//    AND clubrecord.school_year = {0}
//    AND clubrecord.semester = {1}
//ORDER BY
//    class.grade_year
//    , class.display_order
//    , class.class_name
//    , student.seat_no
//    , student.id"
//                        , sy, s);
//                        #endregion

//                        // 取得學生社團資料
//                        DataTable dt = qh.Select(selectSQL);

//                        bgw.ReportProgress(55);
//                        int index = 1;
//                        foreach (DataRow dr in dt.Rows)
//                        {
//                            bgw.ReportProgress(55 + 45 * index / dt.Rows.Count);
//                            int wishLimit = (dr["wish_limit"] == null ? 5 : int.Parse("" + dr["wish_limit"]));
//                            if (index == 1)
//                            {
//                                int count = 6;
//                                int countLimit = count + wishLimit;
//                                for (int i = count; i < countLimit; i++)
//                                {
//                                    ws.Cells.CopyColumn(ws.Cells, 4, i);
//                                    ws.Cells[0, i].PutValue("志願" + (i - 5));
//                                }
//                            }
//                            else
//                                ws.Cells.CopyRow(ws.Cells, 1, index);

//                            ws.Cells[index, 0].PutValue("" + dr["class_name"]);
//                            ws.Cells[index, 1].PutValue("" + dr["seat_no"]);
//                            ws.Cells[index, 2].PutValue("" + dr["name"]);
//                            ws.Cells[index, 3].PutValue("" + dr["student_number"]);
//                            ws.Cells[index, 4].PutValue("" + dr["club_name"]);
//                            ws.Cells[index, 5].PutValue(("" + dr["lock"]) == "true" ? "是" : "");

//                            // 學生志願序
//                            if (dr["content"] != null && "" + dr["content"] != "")
//                            {
//                                XDocument content = XDocument.Parse("" + dr["content"]);
//                                List<XElement> clubList = content.Element("xml").Elements("Club").ToList();
//                                int count = 6;
//                                int countLimit = count + wishLimit - 1;
//                                foreach (XElement club in clubList)
//                                {
//                                    ws.Cells[index, count].PutValue(clubDic[club.Attribute("Ref_Club_ID").Value]);
//                                    count++;
//                                    if (count > countLimit)
//                                        break;
//                                }
//                            }
//                            index++;
//                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    exc = ex;
                }
            };

            bgw.RunWorkerCompleted += delegate
            {
                if (exc == null)
                {
                    #region Excel 存檔
                    {
                        SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
                        SaveFileDialog1.Filter   = "Excel (*.xls)|*.xls|所有檔案 (*.*)|*.*";
                        SaveFileDialog1.FileName = "匯出選社結果(跨部別)";
                        try
                        {
                            if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
                            {
                                wb.Save(SaveFileDialog1.FileName);
                                Process.Start(SaveFileDialog1.FileName);
                                MotherForm.SetStatusBarMessage("匯出選社結果(跨部別),列印完成!!");
                            }
                            else
                            {
                                FISCA.Presentation.Controls.MsgBox.Show("檔案未儲存");
                                return;
                            }
                        }
                        catch
                        {
                            FISCA.Presentation.Controls.MsgBox.Show("檔案儲存錯誤,請檢查檔案是否開啟中!!");
                            MotherForm.SetStatusBarMessage("檔案儲存錯誤,請檢查檔案是否開啟中!!");
                        }
                    }
                    #endregion
                }
                else
                {
                    throw new Exception("匯出選社結果 發生錯誤", exc);
                }
            };

            bgw.RunWorkerAsync();
        }
Example #48
0
        private void Run(string[] args)
        {
            config = new Config(args);

            addToConfigFromFile(config);

            if (printUsage(args.Length))
            {
                return;
            }

            Status result = new Status();

            /* Not needed in production, but it allows you to see what
             *  options actually get set in SS (as a sanity check)
             *  See GMSEC API Users Guide for other settings. */
            config.AddValue("COMMAND_FEEDBACK", "always");

            /* Add the gmdSubject to the connection configuration.
             * This subject needs to be static yet unique amongst GMD clients so
             * that the RTServer can associate a connection with each client.
             * In other words, the GMD subject used here can not be used by any
             * other client in the system. */
            config.AddValue("gmdSubject", "GMSEC.GMD_Subject_publisher");

            /* Set the Server mode, so it 'remembers' if you leave
             * and come back.  See GMSEC API Users Guide for other settings. */
            config.AddValue("SERVER_DISCONNECT_MODE", "warm");

            /* Turn on ether Memory OR File based GMD */
            //cfg.AddValue("IPC_GMD_TYPE","default");  // File based.
            config.AddValue("IPC_GMD_TYPE", "memory");

            // Output GMSEC API version
            Console.Out.WriteLine(ConnectionFactory.GetAPIVersion());

            // Create the connection
            result = ConnectionFactory.Create(config, out conn);
            check("Error creating connection", result);

            // Connect
            result = conn.Connect();
            check("Error connecting", result);

            GMDCallback      gmdcb  = new GMDCallback();
            DispatchCallback dispcb = new DispatchCallback();

            Console.Out.WriteLine("Registering Error Callbacks");
            result = conn.RegisterErrorCallback("CONNECTION_DISPATCHER_ERROR", dispcb);
            check("RegisterErrorCallback", result);
            result = conn.RegisterErrorCallback("SS_GMD_ERROR", gmdcb);
            check("REgisterErrorCallback", result);

            Console.Out.WriteLine("Starting AutoDispatcher\n");
            result = conn.StartAutoDispatch();
            check("startAutoDispatch", result);

            Config msgCfg = new Config();

            /* Required to be set on the Message for GMD.  The T_IPC_DELIVERY_ALL setting says to
             *  assure delivery to ALL subscribers before sending back an ACK.
             *  See GMSEC API Users Guide for other settings. */
            msgCfg.AddValue("SETDELIVERYMODE", "T_IPC_DELIVERY_ALL");

            /* Set Delivery Timeout to 15 seconds.  The Delivery Timeout determines how long the
             * publisher is willing to wait for all subscribers to acknowledge the messaage.  It
             * also determines the size (in units of seconds) of the resend queue.  In this scenario
             * the resend queue would contain 15 seconds worth messages. */
            msgCfg.AddValue("SETDELIVERYTIMEOUT", "15.0");

            result = conn.CreateMessage("GMSEC.TEST.PUBLISH", GMSECMsgKindDefs.PUBLISH, out message,
                                        msgCfg);
            check("CreateMessage", result);

            uint  j  = 1;
            Field fd = new Field();

            fd.SetName("sequence number");
            fd.SetValue(j);
            result = message.AddField(fd);
            check("AddField", result);

            //Publish Message
            result = conn.Publish(message);
            check("Publish", result);
            Console.Out.WriteLine("Published sequence-> " + j);
            while (!result.IsError() ||
                   (result.GetClass() != GMSECErrorClasses.STATUS_MIDDLEWARE_ERROR &&
                    result.GetCode() != GMSECErrorCodes.FIELD_TYPE_MISMATCH))
            {
                j++;
                fd.SetValue(j);
                message.AddField(fd);
                //Publish
                result = conn.Publish(message);
                check("Publish", result);
                Console.Out.WriteLine("Published sequence-> " + j);
                //Sleep a second
                System.Threading.Thread.Sleep(1000);
            }

            //Destroy Message
            result = conn.DestroyMessage(message);
            check("DestroyMessage", result);

            // Disconnect
            result = conn.Disconnect();
            check("Error Disconnecting", result);

            // Destroy the Connection
            result = ConnectionFactory.Destroy(conn);
            check("Error Destroying Connection", result);
            return;
        }
Example #49
0
        public async Task ValidHost_ReturnsTrue()
        {
            await Connection.Connect(LdapServer, DefaultPort);

            Assert.IsTrue(Connection.Connected);
        }
Example #50
0
 public static Task <IConnection> DefaultConnector(string url, ConnectionOptions options, CancellationToken ct)
 {
     return(Connection.Connect(url, options, ct));
 }
Example #51
0
        private void ConfigureWirelessSettingsViaUSBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProgressDialog progress = new ProgressDialog
            {
                Text  = "Configuring NGIMU Wireless Settings",
                Style = ProgressBarStyle.Marquee,
                CancelButtonEnabled = true,
                ProgressMessage     = "",
                Progress            = 0,
                ProgressMaximum     = 1,
                DialogResult        = DialogResult.Cancel,
            };

            ManualResetEvent contiueResetEvent = new ManualResetEvent(false);

            bool hasBeenCanceled = false;

            progress.OnCancel += delegate(object s, FormClosingEventArgs fce)
            {
                hasBeenCanceled = true;
                contiueResetEvent.Set();
            };

            progress.FormClosed += delegate(object s, FormClosedEventArgs fce)
            {
                contiueResetEvent.Set();
            };

            Thread configureWirelessSettingsViaUSBThread = new Thread(() =>
            {
                progress.UpdateProgress(0, "Searching for USB connection.");

                bool found = false;
                ConnectionSearchResult foundConnectionSearchResult = null;

                // search for serial only connections
                using (SearchForConnections searchForConnections = new SearchForConnections(ConnectionSearchTypes.Serial))
                {
                    searchForConnections.DeviceDiscovered += delegate(ConnectionSearchResult connectionSearchResult)
                    {
                        found = true;
                        foundConnectionSearchResult = connectionSearchResult;
                        contiueResetEvent.Set();
                    };

                    contiueResetEvent.Reset();

                    searchForConnections.BeginSearch();

                    contiueResetEvent.WaitOne();

                    searchForConnections.EndSearch();
                }

                if (hasBeenCanceled == true)
                {
                    return;
                }

                if (foundConnectionSearchResult == null)
                {
                    return;
                }

                string deviceDescriptor = foundConnectionSearchResult.DeviceDescriptor;

                // open connection to first device found
                progress.UpdateProgress(0, $"Found device {deviceDescriptor}.");

                using (Connection connection = new Connection(foundConnectionSearchResult))
                {
                    connection.Connect();

                    progress.UpdateProgress(0, $"Restoring default settings.");
                    connection.SendCommand(Command.Default);

                    connection.Settings.WifiMode.Value                  = WifiMode.Client;
                    connection.Settings.WifiClientSSID.Value            = MainForm.DefaultWifiClientSSID;
                    connection.Settings.WifiClientKey.Value             = MainForm.DefaultWifiClientKey;
                    connection.Settings.WifiReceivePort.Value           = MainForm.SynchronisationMasterPort;
                    connection.Settings.SynchronisationMasterPort.Value = MainForm.SynchronisationMasterPort;
                    connection.Settings.SendRateRssi.Value              = MainForm.DefaultSendRateRssi;

                    progress.UpdateProgress(0, $"Writing wireless settings.");
                    this.WriteSettingsWithExistingProgress(progress, new List <ConnectionRow>(), true, new[] { connection.Settings });
                }

                progress.DialogResult = DialogResult.OK;

                Invoke(new MethodInvoker(() => { progress.Close(); }));
            });

            configureWirelessSettingsViaUSBThread.Name = "Configure Wireless Settings Via USB";
            configureWirelessSettingsViaUSBThread.Start();

            if (progress.ShowDialog(this) == DialogResult.OK)
            {
                this.ShowInformation($@"Configuration of device complete.");
            }
        }
Example #52
0
 public void Connect()
 {
     connection.Connect();
 }
Example #53
0
        // return false if user canceled login
        private bool CheckLogin(Connection connection)
        {
            bool result = true;
            bool requireLogin = false;
            P4Command cmd = null;
            try
            {
                if (connection.Server.State == ServerState.Online)
                {
                    cmd = new P4Command(connection, "login", true, "-s");
                    cmd.Run(null);
                }
                else
                {
                    requireLogin = true;
                }
            }
            catch (P4Exception ex)
            {
                if (ex.ErrorLevel >= ErrorSeverity.E_FAILED)
                    //"Perforce password (P4PASSWD) invalid or unset.\n"}    int
                    requireLogin = true;
            }
            finally
            {
                if (cmd != null)
                    cmd.Dispose();
            }

            LoginDialog loginDialog = null;

            while (requireLogin)
            {
                if (loginDialog == null)
                {
                    loginDialog = new LoginDialog();
                    string message = string.Format("For user {0} with workspace {1} on server {2}.".Localize(),
                        connection.UserName, connection.Client.Name, connection.Server.Address.Uri);

                    loginDialog.SetConnectionLabel(message);
                    if ((MainForm != null) && (MainForm.Icon != null))
                        loginDialog.Icon = MainForm.Icon;
                }

                DialogResult dr = loginDialog.ShowDialog(MainForm);
                if (dr == DialogResult.OK)
                {
                    try
                    {
                        if (connection.Server.State != ServerState.Online)
                        {
                            ConnectionOptions["Password"] = loginDialog.Password;
                            connection.Connect(ConnectionOptions);
                            requireLogin = connection.Server.State != ServerState.Online;
                        }
                        else
                        {
                            var credential = connection.Login(loginDialog.Password);
                            requireLogin = credential == null;
                        }
                    }
                    catch (P4Exception e)
                    {
                        ShowErrorMessage(e.Message);
                        if (ThrowExceptions)
                            throw;
                    }
                }
                else
                {
                    result = false;
                    break;
                }
            }
            return result;
        }
Example #54
0
        public void GetUsersTest()
        {
            bool unicode = false;

            string uri       = "localhost:6666";
            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";

            Process p4d = null;

            for (int i = 0; i < 2; i++)             // run once for ascii, once for unicode
            {
                try
                {
                    p4d = Utilities.DeployP4TestServer(TestDir, 6, unicode);
                    Server server = new Server(new ServerAddress(uri));

                    Repository rep = new Repository(server);

                    using (Connection con = rep.Connection)
                    {
                        con.UserName    = user;
                        con.Client      = new Client();
                        con.Client.Name = ws_client;

                        bool connected = con.Connect(null);
                        Assert.IsTrue(connected);

                        Assert.AreEqual(con.Status, ConnectionStatus.Connected);

                        IList <User> u = rep.GetUsers(new Options(UsersCmdFlags.IncludeAll, 2));

                        Assert.IsNotNull(u);
                        Assert.AreEqual(2, u.Count);

                        u = rep.GetUsers(new Options(UsersCmdFlags.IncludeAll, -1), "admin", "Alice");

                        Assert.IsNotNull(u);
                        Assert.AreEqual(2, u.Count);

                        u = rep.GetUsers(new Options(UsersCmdFlags.IncludeAll, 3), "A*");

                        Assert.IsNotNull(u);
                        if (unicode)
                        {
                            Assert.AreEqual(2, u.Count);                             // no user 'Alex' on unicode server
                        }
                        else
                        {
                            Assert.AreEqual(3, u.Count);
                        }

                        //DateTime update = new DateTime(2011, 5, 24, 8, 48, 30);
                        //if (unicode)
                        //{
                        //    update = new DateTime(2011, 5, 24, 9, 15, 12);
                        //}
                        //DateTime access = DateTime.Now;
                        //access = access.Subtract(TimeSpan.FromSeconds(access.Second));
                        //Assert.AreEqual(u[0].Updated,update);
                        //Assert.AreEqual(u[0].Accessed.ToLongDateString(), access.ToLongDateString());
                    }
                }
                finally
                {
                    Utilities.RemoveTestServer(p4d, TestDir);
                }
                unicode = !unicode;
            }
        }
Example #55
0
        public void GetUserTest()
        {
            bool unicode = false;

            string uri       = "localhost:6666";
            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";

            string targetUser    = "******";
            string targetBadUser = "******";

            Process p4d = null;

            for (int i = 0; i < 2; i++) // run once for ascii, once for unicode
            {
                try
                {
                    if (unicode)
                    {
                        targetUser = "******";
                    }

                    p4d = Utilities.DeployP4TestServer(TestDir, 6, unicode);
                    Server server = new Server(new ServerAddress(uri));

                    Repository rep = new Repository(server);

                    using (Connection con = rep.Connection)
                    {
                        con.UserName    = user;
                        con.Client      = new Client();
                        con.Client.Name = ws_client;

                        bool connected = con.Connect(null);
                        Assert.IsTrue(connected);

                        Assert.AreEqual(con.Status, ConnectionStatus.Connected);

                        User u = rep.GetUser(targetUser, null);

                        Assert.IsNotNull(u);
                        Assert.AreEqual(targetUser, u.Id);

                        // test reviews for job093785 user
                        // Алексей has 2 review lines, the bug
                        // would skip the 2nd one
                        if (unicode)
                        {
                            Assert.AreEqual(u.Reviews.Count, 2);
                            Assert.AreEqual(u.Reviews[0], "//depot/MyCode/...");
                            Assert.AreEqual(u.Reviews[1], "//depot/TestData/...");
                        }

                        u = rep.GetUser(targetBadUser, null);

                        Assert.IsNull(u);
                    }
                }
                finally
                {
                    Utilities.RemoveTestServer(p4d, TestDir);
                }
                unicode = !unicode;
            }
        }
Example #56
0
        public void CreateUserWithInvalidFieldTest()
        {
            bool unicode = false;

            string uri       = "localhost:6666";
            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";

            string targetUser        = "******";
            string invalidReviewPath = "test";

            Process p4d = null;

            for (int i = 0; i < 2; i++) // run once for ascii, once for unicode
            {
                try
                {
                    p4d = Utilities.DeployP4TestServer(TestDir, 7, unicode);
                    Server server = new Server(new ServerAddress(uri));

                    Repository rep = new Repository(server);

                    using (Connection con = rep.Connection)
                    {
                        con.UserName    = user;
                        con.Client      = new Client();
                        con.Client.Name = ws_client;

                        bool connected = con.Connect(null);
                        Assert.IsTrue(connected);

                        Assert.AreEqual(con.Status, ConnectionStatus.Connected);

                        User u = new User();
                        u.Id           = targetUser;
                        u.FullName     = "The New Guy";
                        u.Password     = "******";
                        u.EmailAddress = "*****@*****.**";

                        IList <String> reviewList = new List <String>();
                        reviewList.Add(invalidReviewPath);
                        u.Reviews = reviewList;

                        con.UserName = targetUser;
                        connected    = con.Connect(null);
                        Assert.IsTrue(connected);

                        try
                        {
                            User newGuy = rep.CreateUser(u);
                        }
                        catch (P4Exception e)
                        {
                            Assert.AreEqual(839063594, e.ErrorCode, "Error in user specification.\nPath '%invalidReviewPath' is not under '//...'.\n");
                        }
                    }
                }
                finally
                {
                    Utilities.RemoveTestServer(p4d, TestDir);
                }
                unicode = !unicode;
            }
        }
Example #57
0
        /// <summary>
        /// Attempt to connect to the Perforce server
        /// </summary>
        /// <returns>Connection status after the connection attempt</returns>
        public EP4ConnectionStatus Connect()
        {
            // Only attempt to connect if not already successfully connected
            if (ConnectionStatus != EP4ConnectionStatus.P4CS_Connected)
            {
                // Assume disconnected state
                ConnectionStatus = EP4ConnectionStatus.P4CS_Disconnected;

                // Attempt to connect to the server
                try
                {
                    var P4Server = new Server(new ServerAddress(mServerName));

                    mP4Repository = new Repository(P4Server);

                    Connection P4Connection = mP4Repository.Connection;


                    P4Connection.UserName = mUserName;

                    P4Connection.Client = new Client();

                    P4Connection.Connect(null);

                    //Check user connection error, invalid login
                    if (P4Connection.ErrorList != null)
                    {
                        if (P4Connection.ErrorList[0].ErrorCode == 822483067)
                        {
                            Disconnect();
                            ConnectionStatus = EP4ConnectionStatus.P4CS_UserLoginError;
                        }
                        else
                        {
                            Disconnect();
                            ConnectionStatus = EP4ConnectionStatus.P4CS_GeneralError;
                        }
                    }
                    else
                    {
                        Credential LoginCredential = P4Connection.Login(mUserPassword, null, null);
                        if (P4Connection.ErrorList != null)
                        {
                            if (P4Connection.ErrorList[0].ErrorCode == 839195695)
                            {
                                Disconnect();
                                ConnectionStatus = EP4ConnectionStatus.P4CS_UserPasswordLoginError;
                            }
                            else
                            {
                                Disconnect();
                                ConnectionStatus = EP4ConnectionStatus.P4CS_GeneralError;
                            }
                        }
                        else
                        {
                            P4Connection.Credential = LoginCredential;
                            ConnectionStatus        = EP4ConnectionStatus.P4CS_Connected;
                        }
                    }
                }
                // Disconnect and return an error status if an exception was thrown
                catch (P4Exception ex)
                {
                    if (ex.ErrorCode == 841354277)
                    {
                        //Could not connect to the server
                        Disconnect();
                        ConnectionStatus = EP4ConnectionStatus.P4CS_ServerLoginError;
                    }
                    else
                    {
                        //unknown error
                        Disconnect();
                        ConnectionStatus = EP4ConnectionStatus.P4CS_GeneralError;
                    }
                }
            }
            return(ConnectionStatus);
        }
        private string ConvertDSNS(string name)
        {
            if(name.StartsWith("http://",true,CultureInfo.CurrentCulture))
                return name;

            if(name.StartsWith("https://",true,CultureInfo.CurrentCulture))
                return name;

            Connection con = new Connection();
            con.EnableSession = false;
            con.EnableSecureTunnel = false;
            con.Connect("http://dsns1.ischool.com.tw/dsns/", "dsns", new PublicSecurityToken());

            XmlHelper h = new XmlHelper("<a>" + name + "</a>");
            Envelope env = con.SendRequest("DS.NameService.GetDoorwayURL", new Envelope(h));
            h = new XmlHelper(env.Body);
            string value = h.GetText(".");
            if (string.IsNullOrWhiteSpace(value))
                throw new Exception("DSNS 名稱解析失敗");
            return value;
        }
Example #59
0
        protected IEnumerator _doLoginToGameSvr(string strName, string pwd, Action <Constants, PlayerData> callback)
        {
            bool    bIsDone = false;
            Message retMsg  = null;

            _connection.Connect(_gameSvrIP, _gameSvrPort, retMsg_ =>
            {
                bIsDone = true;
                retMsg  = retMsg_;
            });

            yield return(new WaitUntil(() => bIsDone));

            if (retMsg.id != Connection.SYS_MSG_CONNECTED)
            {
                var reason = (string)retMsg.jsonObj["reason"];
                Debug.Log(reason);
                if (callback != null)
                {
                    callback(Constants.NETWORK_ERROR, null);
                }
                yield break;
            }

            bIsDone = false;
            _connection.Handshake(new JsonObject(), data => { bIsDone = true; });

            yield return(new WaitUntil(() => bIsDone));

            bIsDone = false;

            JsonObject msg = new JsonObject();

            msg["uid"]      = 1;
            msg["password"] = pwd;
            Message message = null;

            //"MessageEnterGame
            _connection.Request(RequestMsg.REQUEST_ENTER, msg, retMsg_ =>
            {
                bIsDone = true;
                message = retMsg_;
            });

            yield return(new WaitUntil(() => bIsDone));

            bIsDone = false;

            MessageEnterGame result = JsonReader.Deserialize <MessageEnterGame>(message.rawString);

            //Constants code = (Constants)Enum.Parse(typeof(Constants), message.jsonObj["code"].ToString());

            if (result.code == Constants.SUCCESS)
            {
                loginState = LoginState.Logined;

                _connection.RemoveEventListeners(Connection.DisconnectEvent);
                _connection.ListenTo(Connection.DisconnectEvent, _onDisconnect);
                this._strUserName = strName;
                this._strPwd      = pwd;
            }

            if (callback != null)
            {
                callback(result.code, result.playerData);
            }
        }
 private void InitSchoolYear()
 {
     Connection conn = new Connection();
     try
     {
         conn.EnableSession = false;
         conn.Connect(
             "j.kh.edu.tw",
             "centraloffice",
             FISCA.Authentication.DSAServices.AccessPoint,
             FISCA.Authentication.DSAServices.AccessPoint
         );
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return;
     }
     //var result = ContractService.GetOpenDate(Connection); FISCA.Authentication.DSAServices.AccessPoint
     //< Response >
     //< data >
     //  < uid > 7448 </ uid >
     //  < last_update > 2015 - 07 - 09 17:57:22.974804 </ last_update >
     //  < school_year > 103 </ school_year >
     //  < start_date > 2015 - 07 - 01 00:00:00 </ start_date >
     //  < end_date > 2015 - 07 - 31 00:00:00 </ end_date >
     //</ data >
     //< data >
     //  < uid > 7448 </ uid >
     //  < last_update > 2015 - 07 - 09 17:57:22.974804 </ last_update >
     //  < school_year > 103 </ school_year >
     //  < start_date > 2015 - 07 - 01 00:00:00 </ start_date >
     //  < end_date > 2015 - 07 - 31 00:00:00 </ end_date >
     //</ data >
     //</Response>
     XElement result;
     try
     {
         result = ContractService.GetSurveyYears(conn);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return;
     }
     this.txtSurveyYear.Minimum = result.Descendants("school_year").Min(x => decimal.Parse(x.Value));
     this.txtSurveyYear.Maximum = result.Descendants("school_year").Max(x => decimal.Parse(x.Value));
     this.txtSurveyYear.Value = this.txtSurveyYear.Maximum;
     this.CurrentSchoolYear = this.txtSurveyYear.Value;
 }