Exemplo n.º 1
0
        static void Accept_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket client = e.AcceptSocket;
             Socket server = sender as Socket;

             if (sender == null) return;

             SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs();
             SocketAsyncEventArgs receciveArg = new SocketAsyncEventArgs();

             ConnectInfo info = new ConnectInfo();
             info.tmpList = new ArrayList();
             info.SendArg = sendArg;
             info.ReceiveArg = receciveArg;
             info.ServerSocket=server;

             byte[] sendbuffers=Encoding.ASCII.GetBytes("welcome\n");
             sendArg.SetBuffer(sendbuffers, 0, sendbuffers.Length);

             sendbuffers=new byte[1024];
             receciveArg.SetBuffer(sendbuffers, 0, 1024);
             receciveArg.UserToken = info;
             receciveArg.Completed += new EventHandler<SocketAsyncEventArgs>(Rececive_Completed);

             client.SendAsync(sendArg);
             client.ReceiveAsync(receciveArg);

             e.Dispose();
        }
Exemplo n.º 2
0
        public static bool DeviceLogFile_View(string appName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                try
                {
                    // Setup
                    string logFile = Application.temporaryCachePath + @"/deviceLog.txt";

                    // Download the file
                    string query = string.Format(kAPI_FileQuery, connectInfo.IP);
                    query += "?knownfolderid=LocalAppData";
                    query += "&filename=UnityPlayer.log";
                    query += "&packagefullname=" + QueryAppDetails(appName, connectInfo).PackageFullName;
                    query += "&path=%5C%5CTempState";
                    client.DownloadFile(query, logFile);

                    // Open it up in default text editor
                    System.Diagnostics.Process.Start(logFile);
                }
                catch (System.Exception ex)
                {
                    Debug.LogError(ex.ToString());
                    return false;
                }
            }

            return true;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Find the edges that connect this POI to a track
 /// </summary>
 /// <param name="track">track</param>
 /// <param name="points">points on the track</param>
 /// <param name="trackStart">first vertex on the track</param>
 public void FindEdges(Edge track, List<Vertex> points)
 {
     ConnectInfo ci = null;
     for (int idx = 0; idx < points.Count; idx++)
     {
         Vertex point = points[idx];
         Edge edge = new Edge(this, point);
         if ((ShortestEdge == null) || (edge.Weight < ShortestEdge.Weight))
         {
             ShortestEdge = edge;
             ClosestTrackIndex = idx;
             ClosestTrack = track.Track;
         }
         if (edge.Weight < Graph.MinDist)
         {
             if (ci == null || ci.dist > edge.Weight)
                 ci = new ConnectInfo(track, point, idx, edge.Weight);
         }
     }
     // Add the connection if it was found
     if (ci != null)
     {
         Connections.Add(ci);
         Edges.Add(ci.track);
         track.AddPoint(this, ci.index);
     }
 }
Exemplo n.º 4
0
        public static bool connect()
        {
            //initialize the connection info class
            DAServer = new DaServerMgt();
            connectInfo = new ConnectInfo();

            string url = "opcda://localhost/Kepware.KEPServerEX.V5/{B3AF0BF6-4C0C-4804-A122-6F3B160F4397}";

            int clientHandle = 1;

            //initialize the connect info object data
            connectInfo.LocalId = "en";
            connectInfo.KeepAliveTime = 5000;
            connectInfo.RetryAfterConnectionError = true;
            connectInfo.RetryInitialConnection = true;
            connectInfo.ClientName = "IDCServer";

            bool connectFailed = false;

            try
            {
                logger.Info("Connecting to DAServer: {0}, {1}, {2}", url, clientHandle, connectInfo.ToString());
                DAServer.Connect(url, clientHandle, ref connectInfo, out connectFailed);

                // Update our connection status
                if (!connectFailed)
                {
                    logger.Info("Connection Succeeded");
                    return true;
                }
                else
                {
                    logger.Error("Connection Failed");
                    return false;
                }
            }
            catch (Exception e)
            {
                logger.Error("Handled connect exception. Reason: " + e.Message);
                throw e;
            }
        }
Exemplo n.º 5
0
        public bool Connect()
        {
            bool connect = false;

            try
            {
                String      s  = CultureInfo.CurrentCulture.Name;
                ConnectInfo ci = new ConnectInfo();
                ci.ClientName                = "Kepware.KEPServerEX.V6";
                ci.LocalId                   = s;// "en";
                ci.KeepAliveTime             = 10000;
                ci.RetryAfterConnectionError = true;
                ci.RetryInitialConnection    = true;


                ci.RetryInitialConnection = true;
                _daServerMgt = new DaServerMgt();

                bool   connectFailed = false;
                int    clientHandle  = 1;
                string url           = getOPCServeurURL();

                _daServerMgt.Connect(url, clientHandle, ref ci, out connectFailed);

                if (!connectFailed)
                {
                    connect = true;
                }
                else
                {
                }
            }
            catch (Exception e)
            {
                Writer.writeAll("Handled Connect exception. Reason: " + e.ToString());
                connect = false;
            }
            return(connect);
        }
Exemplo n.º 6
0
 private void RegistForm_Load(object sender, EventArgs e)
 {
     try
     {
         DataTable dt    = null;
         string    error = "";
         ConnectInfo.LoadUser(out dt, out error);
         if (dt != null)
         {
             this.dgvUser.DataSource = dt;
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex);
         if (this.aiFace != null)
         {
             this.aiFace.Stop();
             this.aiFace = null;
         }
     }
 }
Exemplo n.º 7
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            ConnectInfo = new ConnectInfo(txtServerName.Text, txtUsername.Text, txtPassword.Text, cbbAuthencation.SelectedIndex);

            if (chkRememberPassword.Checked)
            {
                Settings.Default.Username = txtUsername.Text;
                Settings.Default.Password = txtPassword.Text;
                Settings.Default.SavePassword = true;
            }
            else
            {
                Settings.Default.Username = txtUsername.Text;
                Settings.Default.Password = "";
                Settings.Default.SavePassword = false;
            }
            Settings.Default.ServerName = txtServerName.Text;
            Settings.Default.KetNoi = GetConnect(cbbAuthencation.SelectedIndex).ConnectionString;
            Settings.Default.Save();
            Utility.SaveConfig(txtServerName.Text, Settings.Default.KetNoi);
            //btnExit_Click(null, null);
        }
Exemplo n.º 8
0
        public void ESBAddConnect(IDbConnection cn, ConnectInfo entity)
        {
            using (OracleCommand cmd = new OracleCommand())
            {
                cmd.Connection = cn as OracleConnection;
                cmd.BindByName = true;

                cmd.CommandText  = "SELECT BPMSEQ_ESB_CONNECTINFO.NEXTVAL FROM DUAL";
                entity.connectId = System.Convert.ToInt32(cmd.ExecuteScalar());

                cmd.CommandText = @"INSERT INTO ESB_CONNECTINFO(CONNECTID,CONNECTNAME,CONNECTTYPE,CAPTION,CONNECTSTR,CREATETIME,UPDATETIME,ISVALID) VALUES (:CONNECTID,:CONNECTNAME,:CONNECTTYPE,:CAPTION,:CONNECTSTR,:CREATETIME,:UPDATETIME,:ISVALID)";
                cmd.Parameters.Add(":CONNECTID", OracleDbType.Int32).Value       = (int)entity.connectId;
                cmd.Parameters.Add(":CONNECTNAME", OracleDbType.NVarchar2).Value = entity.connectName;
                cmd.Parameters.Add(":CONNECTTYPE", OracleDbType.NVarchar2).Value = entity.connectType.ToString();
                cmd.Parameters.Add(":CAPTION", OracleDbType.NVarchar2).Value     = entity.caption;
                cmd.Parameters.Add(":CONNECTSTR", OracleDbType.NVarchar2).Value  = entity.connectStr;
                cmd.Parameters.Add(":CREATETIME", OracleDbType.Date).Value       = entity.createTime;
                cmd.Parameters.Add(":UPDATETIME", OracleDbType.Date).Value       = entity.updateTime;
                cmd.Parameters.Add(":ISVALID", OracleDbType.Int16).Value         = this.ConvertBoolToInt16(entity.isvalid);
                cmd.ExecuteNonQuery();
            }
        }
        /// <summary>详细内容界面</summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public ActionResult Detail(string options)
        {
            // 所属应用信息
            ApplicationInfo application = ViewBag.application = AppsContext.Instance.ApplicationService[ConnectConfiguration.ApplicationName];

            // 管理员身份标记
            bool isAdminToken = ViewBag.isAdminToken = AppsSecurity.IsAdministrator(this.Account, application.ApplicationName);

            JsonData request = JsonMapper.ToObject(options == null ? "{}" : options);

            // 实体数据标识
            string id = !request.Keys.Contains("id") ? string.Empty : request["id"].ToString();

            ConnectInfo param = null;

            if (!string.IsNullOrEmpty(id))
            {
                param = ConnectContext.Instance.ConnectService.FindOne(id);
            }

            if (param == null)
            {
                ApplicationError.Write(404);
            }

            // -------------------------------------------------------
            // 数据加载
            // -------------------------------------------------------

            ViewBag.Title = string.Format("{0}-{1}-{2}", param.Name, application.ApplicationDisplayName, this.SystemName);

            // 加载当前业务实体数据
            ViewBag.entityClassName = KernelContext.ParseObjectType(param.GetType());
            // 加载当前业务实体数据
            ViewBag.param = param;

            return(View("/views/main/connect/connect-detail.cshtml"));
        }
Exemplo n.º 10
0
        public static bool DeviceLogFile_View(string packageFamilyName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                try
                {
                    // Setup
                    string logFile = Application.temporaryCachePath + @"/deviceLog.txt";

                    // Get the app details...
                    AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
                    if (appDetails == null)
                    {
                        Debug.LogError("Application not found on target device (" + packageFamilyName + ")");
                        return(false);
                    }

                    // Download the file
                    string query = string.Format(API_FileQuery, connectInfo.IP);
                    query += "?knownfolderid=LocalAppData";
                    query += "&filename=UnityPlayer.log";
                    query += "&packagefullname=" + appDetails.PackageFullName;
                    query += "&path=%5C%5CTempState";
                    client.DownloadFile(query, logFile);

                    // Open it up in default text editor
                    Process.Start(logFile);
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.ToString());
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 11
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCallsign.Text))
            {
                ErrorFocus("Please enter a callsign", txtCallsign);
                return;
            }
            else if (string.IsNullOrEmpty(txtTypeCode.Text))
            {
                ErrorFocus("Please enter the aircraft type code", txtTypeCode);
                return;
            }
            else if (!string.IsNullOrEmpty(txtSelcalCode.Text))
            {
                if (!ValidateSelcal(txtSelcalCode.Text))
                {
                    return;
                }
            }
            else if (mTypeCodes.Count(o => o.Identifier == txtTypeCode.Text.ToUpper()) == 0)
            {
                if (MessageBox.Show(this, string.Format("The aircraft type code {0} appears to be invalid. This can prevent other users from seeing your aircraft correctly. Are you sure you want to connect using this invalid type code?", txtTypeCode.Text.ToUpper()), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.No)
                {
                    DialogResult = DialogResult.None;
                    txtTypeCode.Select();
                    return;
                }
            }
            ConnectInfo info = new ConnectInfo(txtCallsign.Text, txtTypeCode.Text, txtSelcalCode.Text, chkObserverMode.Checked);

            mConfig.RecentConnectionInfo.RemoveAll(o => o.Equals(info));
            mConfig.RecentConnectionInfo.Insert(0, info);
            if (mConfig.RecentConnectionInfo.Count > 20)
            {
                mConfig.RecentConnectionInfo.RemoveRange(20, mConfig.RecentConnectionInfo.Count - 20);
            }
            mConfig.SaveConfig();
        }
Exemplo n.º 12
0
        public override void FindGame(Google.ProtocolBuffers.IRpcController controller, FindGameRequest request, Action <FindGameResponse> done)
        {
            FindGameResponse.Builder findGameResponse = FindGameResponse.CreateBuilder();
            findGameResponse.SetRequestId(12526585062881647236);

            done(findGameResponse.Build());

            //client.ListenerId = request.ObjectId;

            GameFoundNotification.Builder gameFoundNotification = GameFoundNotification.CreateBuilder();

            GameHandle.Builder gameHandle = GameHandle.CreateBuilder();
            gameHandle.SetFactoryId(request.FactoryId);
            gameHandle.SetGameId(bnet.protocol.EntityId.CreateBuilder().SetHigh(433661094641971304).SetLow(11017467167309309688).Build());

            ConnectInfo.Builder connectInfo = ConnectInfo.CreateBuilder();
            connectInfo.SetToonId(new bnet.protocol.EntityId.Builder {
                High = 216174302532224051,
                Low  = 2
            }.Build());
            connectInfo.SetHost("127.0.0.1");
            connectInfo.SetPort(6665);
            connectInfo.SetToken(ByteString.CopyFrom(new byte[] { 0x07, 0x34, 0x02, 0x60, 0x91, 0x93, 0x76, 0x46, 0x28, 0x84 }));
            connectInfo.AddAttribute(Attribute
                                     .CreateBuilder()
                                     .SetName("SGameId")
                                     .SetValue(Variant
                                               .CreateBuilder()
                                               .SetIntValue(2014314530)
                                               .Build())
                                     .Build());

            gameFoundNotification.SetRequestId(12526585062881647236);
            gameFoundNotification.SetGameHandle(gameHandle.Build());
            gameFoundNotification.AddConnectInfo(connectInfo.Build());

            client.GetImportedService <GameFactorySubscriber>().NotifyGameFound(controller, gameFoundNotification.Build(), r => { });
        }
Exemplo n.º 13
0
 private void FrmMain_MdiChildActivate(object sender, EventArgs e)
 {
     foreach (TreeNode item in tvConnectList.Nodes[0].Nodes)
     {
         ConnectInfo info = (ConnectInfo)item.Tag;
         if (info.FrmDataBase != null && info.FrmDataBase == this.ActiveMdiChild)
         {
             tvConnectList.SelectedNode = item;
             break;
         }
     }
     foreach (ToolStripMenuItem item in tssbWins.DropDownItems)
     {
         if (item.Tag == this.ActiveMdiChild)
         {
             item.Checked = true;
         }
         else
         {
             item.Checked = false;
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// 测试数据连接
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public JObject TestConnect(HttpContext context)
        {
            JObject     obj     = new JObject();
            YZRequest   request = new YZRequest(context);
            bool        flag    = false;
            string      message = null;
            ConnectInfo entity  = ConnectInfoManager.GetConnectInfo(request.GetInt32("connectId", -1));

            switch (entity.connectType)
            {
            case SourceTypeEnum.Excel:
                flag = CommonHandle.IsExcelJoin(JObject.Parse(entity.connectStr).ToObject <ExcelLogin>(), out message);
                break;

            case SourceTypeEnum.Oracle:
                flag = CommonHandle.IsOracleJoin(JObject.Parse(entity.connectStr).ToObject <OracleLogin>(), out message);
                break;

            case SourceTypeEnum.SAP:
                flag = CommonHandle.IsSapJoin(JObject.Parse(entity.connectStr).ToObject <SapLogin>(), out message);
                break;

            case SourceTypeEnum.SqlServer:
                flag = CommonHandle.IsSqlServerJoin(JObject.Parse(entity.connectStr).ToObject <SqlServerLogin>(), out message);
                break;

            case SourceTypeEnum.WebService:
                flag = CommonHandle.IsWebServiceJoin(JObject.Parse(entity.connectStr).ToObject <WebServiceLogin>(), out message);
                break;

            default:
                break;
            }
            obj[YZJsonProperty.success]      = flag;
            obj[YZJsonProperty.errorMessage] = flag ? "连接成功!" : String.Format("连接失败!原因:<br/>{0}", message);
            return(obj);
        }
Exemplo n.º 15
0
        private void ReceiveCallBack(IAsyncResult asyncResult)
        {
            ConnectInfo connection = asyncResult.AsyncState as ConnectInfo;

            try
            {
                Socket      senderSocket = connection.Socket;
                SocketError response;
                int         buffSize = senderSocket.EndReceive(asyncResult, out response);

                if (response == SocketError.Success)
                {
                    byte[] payload = new byte[buffSize];
                    Array.Copy(connection.Data, payload, payload.Length);

                    Handler.Handle(payload, connection);
                }
            }catch (Exception e)
            {
                Console.WriteLine($"Can't receive data: {e.Message}");
            }
            finally
            {
                try
                {
                    connection.Socket.BeginReceive(connection.Data, 0, connection.Data.Length, SocketFlags.None, ReceiveCallBack, connection);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"{e.Message}");
                    var address = connection.Socket.RemoteEndPoint.ToString();

                    ConnectStorage.Remove(address);
                    connection.Socket.Close();
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 返回访问结果
        /// </summary>
        /// <param name="info"></param>
        /// <param name="connect"></param>
        /// <returns></returns>
        private DataTable GetResult(QueryDepictInfo info, ConnectInfo connect)
        {
            ISourceHandle handle = null;

            switch (connect.connectType)
            {
            case SourceTypeEnum.Excel:
                handle = new ExcelHandle(JObject.Parse(connect.connectStr).ToObject <ExcelLogin>());
                break;

            case SourceTypeEnum.Oracle:
                handle = new OracleHandle(JObject.Parse(connect.connectStr).ToObject <OracleLogin>());
                break;

            case SourceTypeEnum.SAP:
                handle = new SapHandle(JObject.Parse(connect.connectStr).ToObject <SapLogin>());
                break;

            case SourceTypeEnum.SqlServer:
                handle = new SqlServerHandle(JObject.Parse(connect.connectStr).ToObject <SqlServerLogin>());
                break;

            case SourceTypeEnum.WebService:
                handle = new WebServiceHandle(JObject.Parse(connect.connectStr).ToObject <WebServiceLogin>());
                break;

            default:
                break;
            }
            DataTable dt = new DataTable();

            if (handle != null)
            {
                dt = handle.GetResult(info);
            }
            return(dt);
        }
Exemplo n.º 17
0
        public Client(ILog log, string hostnameAndPort)
        {
            this.log = log;
            var port = new UdpClient();

            connector = new Connector(log, 30, port, true);
            var info = new ConnectInfo
            {
                BriskVersion = new NameVersion
                {
                    Version = new Version(1, 0, 0, ""),
                    Name    = "brisk"
                },
                SdkVersion = new NameVersion
                {
                    Version = new Version(1, 0, 0, ""),
                    Name    = "unknown"
                },
                SchemaVersion = new NameVersion
                {
                    Version = new Version(1, 0, 0, ""),
                    Name    = "schema"
                },
                ApplicationVersion = new NameVersion
                {
                    Version = new Version(1, 0, 0, ""),
                    Name    = "brisk"
                },
                Payload = new CustomConnectPayload
                {
                    Payload = new byte[] { 0x08 },
                },
            };

            connector.Connect(hostnameAndPort, info);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Kills the target application on the target device.
        /// </summary>
        /// <param name="packageFamilyName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="showDialog"></param>
        /// <returns>true, if application was successfully stopped.</returns>
        public static bool KillApp(string packageFamilyName, ConnectInfo targetDevice, bool showDialog = true)
        {
            AppDetails appDetails = QueryAppDetails(packageFamilyName, targetDevice);

            if (appDetails == null)
            {
                Debug.LogError("Application not found");
                return(false);
            }

            string query = string.Format("{0}?package={1}",
                                         string.Format(API_AppQuery, FinalizeUrl(targetDevice.IP)),
                                         WWW.EscapeURL(EncodeTo64(appDetails.PackageFullName)));

            bool        success       = WebRequestDelete(query, GetBasicAuthHeader(targetDevice), showDialog);
            MachineName targetMachine = GetMachineName(targetDevice);

            if (success)
            {
                Debug.LogFormat("Successfully stopped {0} on {1}.", packageFamilyName, targetMachine.ComputerName);
            }

            return(success);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Handles completion of the connect.
        /// </summary>
        /// <param name="ar">The async result.</param>
        private void OnDNSResolve(IAsyncResult ar)
        {
            ConnectInfo info = (ConnectInfo)ar.AsyncState;
            IPAddress   addr = null;

            using (TimedLock.Lock(router.SyncRoot))
            {
                try
                {
                    // $hack(jeff.lill):
                    //
                    // It's possible but very unlikely that only IPv6 addresses will be returned
                    // by the DNS and the array indexing operation will throw an exception.  The
                    // end result will be correct, since we don't handle IPv6 yet.

                    addr = Dns.EndGetHostEntry(ar).AddressList.IPv4Only()[0];
                    router.Trace(2, "TCP: DNS Resolve", "Host=" + info.Host + " Address=" + addr.ToString(), null);
                }
                catch (Exception e)
                {
                    router.Trace("TCP: DNS Resolve Failed [" + info.Host + "]", e);
                    router.OnTcpClose(this);
                    Close();
                    return;
                }

                try
                {
                    Connect(new IPEndPoint(addr, info.Port), info.Msg);
                }
                catch (Exception e)
                {
                    router.Trace(string.Format(null, "TCP: Connect Failed [{0},{1}:{2}]", info.Host, addr, info.Port), e);
                }
            }
        }
Exemplo n.º 20
0
 private void btnLogin_Click(object sender, EventArgs e)
 {
     try
     {
         string error;
         bool   rslt = ConnectInfo.Login(this.txtUser.Text, this.txtPassword.Text, out error);
         if (!rslt)
         {
             this.tipMsg.Show(error, this.txtUser);
         }
         else
         {
             string  args     = $"-user {this.txtUser.Text} -password {this.txtPassword.Text}";
             string  fileName = Application.ExecutablePath;
             Process proc     = Process.Start(fileName, args);
             proc.WaitForInputIdle();
             Application.Exit();
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Downloads and launches the Log file for the target application on the target device.
        /// </summary>
        /// <param name="packageFamilyName"></param>
        /// <param name="targetDevice"></param>
        /// <returns>True, if download success.</returns>
        public static bool DeviceLogFile_View(string packageFamilyName, ConnectInfo targetDevice)
        {
            EditorUtility.DisplayProgressBar("Download Log", "Downloading Log File for " + packageFamilyName, 0.25f);

            AppDetails appDetails = QueryAppDetails(packageFamilyName, targetDevice);

            if (appDetails == null)
            {
                Debug.LogWarningFormat("{0} not installed on target device", packageFamilyName);
                EditorUtility.ClearProgressBar();
                return(false);
            }

            string logFile = string.Format("{0}/{1}_{2}{3}{4}{5}{6}{7}_deviceLog.txt",
                                           Application.temporaryCachePath,
                                           targetDevice.MachineName,
                                           DateTime.Now.Year,
                                           DateTime.Now.Month,
                                           DateTime.Now.Day,
                                           DateTime.Now.Hour,
                                           DateTime.Now.Minute,
                                           DateTime.Now.Second);

            string response = WebRequestGet(string.Format(API_FileQuery, FinalizeUrl(targetDevice.IP), appDetails.PackageFullName), GetBasicAuthHeader(targetDevice, true));
            bool   success  = !string.IsNullOrEmpty(response);

            if (success)
            {
                File.WriteAllText(logFile, response);
                Process.Start(logFile);
            }

            EditorUtility.ClearProgressBar();

            return(success);
        }
Exemplo n.º 22
0
            /// <summary>
            /// Constructs manager from XmlElement
            /// </summary>
            /// <param name="xmlElement"></param>
            /// <returns></returns>
            public static TorrentManager FromXml(XmlElement xmlElement)
            {
                TorrentManager torrentManager = new TorrentManager();

                foreach (XmlElement e in xmlElement["torrents"])
                {
                    Torrent t = Torrent.CreateFromXml(e);
                    torrentManager.Add(t); //later automatic start
                }

                torrentManager.ForceIp = bool.Parse(xmlElement["forceip"].InnerText);
                ConnectInfo loadedConnectInfo = ConnectInfo.ParseXml(xmlElement[ConnectInfo.XmlName]);

                if (torrentManager.ForceIp)
                {
                    torrentManager.MyConnectInfo = loadedConnectInfo;
                }
                else
                {
                    torrentManager.MyConnectInfo = new ConnectInfo(GetLocalIpAddress(), loadedConnectInfo.Port);
                }

                return(torrentManager);
            }
Exemplo n.º 23
0
 public void SaveConnectInfos()
 {
     try
     {
         List <DbConnectConfigure> configures = new List <DbConnectConfigure>();
         foreach (TreeNode item in this.tvConnectList.Nodes[0].Nodes)
         {
             ConnectInfo info = (ConnectInfo)item.Tag;
             configures.Add(info.DbConnectConfigure);
         }
         string       path = Application.StartupPath + "\\connectconfigures.json";
         FileStream   fs   = File.Open(path, FileMode.Create);
         StreamWriter sw   = new StreamWriter(fs);
         sw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(configures));
         sw.Flush();
         sw.Close();
         sw.Dispose();
         fs.Dispose();
     }
     catch (Exception ex)
     {
         //MessageBox.Show("保存配置异常!");
     }
 }
Exemplo n.º 24
0
 private void tsbtnAddDriver_Click(object sender, EventArgs e)
 {
     try
     {
         UpLoadDriverForm form = new UpLoadDriverForm();
         if (form.ShowDialog() == DialogResult.OK)
         {
             bool rslt = ConnectInfo.AddDriver(form.ConnectInfo);
             if (rslt)
             {
                 AccordionControlElement element = new AccordionControlElement(ElementStyle.Item);
                 element.Text  = form.ConnectInfo.DriverName;
                 element.Image = form.ConnectInfo.OpenImage;
                 element.Tag   = form.ConnectInfo;
                 this.accDataSource.Elements[0].Elements.Add(element);
                 this.accDataSource.SelectedElement = element;
             }
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex);
     }
 }
Exemplo n.º 25
0
        // -------------------------------------------------------
        // 保存 删除
        // -------------------------------------------------------

        #region 函数:Save(ConnectInfo param)
        /// <summary>保存记录</summary>
        /// <param name="param"><see cref="ConnectInfo"/>实例详细信息</param>
        /// <param name="message">数据库操作返回的相关信息</param>
        /// <returns><see cref="ConnectInfo"/>实例详细信息</returns>
        public ConnectInfo Save(ConnectInfo param)
        {
            if (string.IsNullOrEmpty(param.Id))
            {
                throw new Exception("实例标识不能为空。");
            }

            bool isNewObject = !this.IsExist(param.Id);

            string methodName = isNewObject ? "新增" : "编辑";

            if (isNewObject)
            {
                IAccountInfo account = KernelContext.Current.User;

                param.AccountId   = account.Id;
                param.AccountName = account.Name;
            }

            // 过滤 Cross Site Script
            param = StringHelper.ToSafeXSS <ConnectInfo>(param);

            return(this.provider.Save(param));
        }
Exemplo n.º 26
0
        /// <summary>查询某条记录</summary>
        /// <param name="appKey">AppKey</param>
        /// <returns>返回一个实例<see cref="ConnectInfo"/>的详细信息</returns>
        public ConnectInfo FindOneByAppKey(string appKey)
        {
            ConnectInfo param = null;

            // 初始化缓存
            if (this.cacheStorage.Count == 0)
            {
                IList <ConnectInfo> list = this.FindAll();

                foreach (ConnectInfo item in list)
                {
                    this.cacheStorage.Add(item.AppKey, item);
                }
            }

            // 查找缓存数据
            if (this.cacheStorage.ContainsKey(appKey))
            {
                param = this.cacheStorage[appKey];
            }

            // 如果缓存中未找到相关数据,则查找数据库内容
            return(param == null?this.provider.FindOneByAppKey(appKey) : param);
        }
Exemplo n.º 27
0
        public void OnWindowEnabled()
        {
            UnityConnect.instance.StateChanged     += OnConnectStateChanged;
            Collab.instance.StateChanged           += OnCollabStateChanged;
            Collab.instance.RevisionUpdated        += OnCollabRevisionUpdated;
            Collab.instance.JobsCompleted          += OnCollabJobsCompleted;
            Collab.instance.ErrorOccurred          += OnCollabError;
            Collab.instance.ErrorCleared           += OnCollabErrorCleared;
            EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
            m_Service.FetchRevisionsCallback       += OnFetchRevisions;

            m_ConnectState = UnityConnect.instance.GetConnectInfo();
            m_CollabState  = Collab.instance.GetCollabInfo();

            m_Window.revisionActionsEnabled = !EditorApplication.isPlayingOrWillChangePlaymode;

            // Setup window callbacks
            m_Window.OnPageChangeAction   = OnUpdatePage;
            m_Window.OnUpdateAction       = OnUpdate;
            m_Window.OnRestoreAction      = OnRestore;
            m_Window.OnGoBackAction       = OnGoBack;
            m_Window.OnShowBuildAction    = ShowBuildForCommit;
            m_Window.OnShowServicesAction = ShowServicePage;
            m_Window.itemsPerPage         = k_ItemsPerPage;

            // Initialize data
            UpdateBuildServiceStatus();
            var state = RecalculateState();

            // Only try to load the page if we're ready
            if (state == HistoryState.Ready)
            {
                OnUpdatePage(m_CurrentPage);
            }
            m_Window.UpdateState(state, true);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Returns a dataset override to use (if any) instead of the project's dataset.  If there is no dataset override
 /// <i>null</i> is returned and the project's dataset is used.
 /// </summary>
 /// <param name="nProjectID">Specifies the project ID associated with the trainer (if any)</param>
 /// <param name="ci">Optionally, specifies the database connection information (default = null).</param>
 public DatasetDescriptor GetDatasetOverride(int nProjectID, ConnectInfo ci = null)
 {
     return(get_dataset_override(nProjectID, ci));
 }
Exemplo n.º 29
0
        public static bool UninstallApp(string appName, ConnectInfo connectInfo)
        {
            try
            {
                // Find the app description
                AppDetails appDetails = QueryAppDetails(appName, connectInfo);
                if (appDetails == null)
                {
                    Debug.LogError(string.Format("Application '{0}' not found", appName));
                    return false;
                }

                // Setup the command
                string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
                query += "?package=" + WWW.EscapeURL(appDetails.PackageFullName);

                // Use HttpWebRequest for a delete query
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
                request.Timeout = TimeoutMS;
                request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                request.Method = "DELETE";
                using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
                {
                    Debug.Log("Response = " + httpResponse.StatusDescription);
                    httpResponse.Close();
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.ToString());
                return false;
            }

            return true;
        }
Exemplo n.º 30
0
        private void ConnectThread(object data)
        {
            try
            {
                ConnectInfo ci = data as ConnectInfo;

                int handle = -1;
                int status = -1;

                UpdateConnectionStatus("Connecting...");
                if (ci.Remote == true)
                {
                    ErrorLog.WriteLine(string.Format("Connecting to Remote Host ({0}, {1}, {2})...", ci.Ip, ci.User, ci.Pass));
                    NMPRK.nmprk_connect_remote_parameters_t input = new NMPRK.nmprk_connect_remote_parameters_t();
                    input.ipOrHostname = ci.Ip;
                    input.username     = ci.User;
                    input.password     = ci.Pass;
                    status             = NMPRK.NMPRK_API.ConnectRemote(ref input, ref handle);
                }
                else
                {
                    ErrorLog.WriteLine("Connecting to Local Host...");
                    status = NMPRK.NMPRK_API.ConnectLocal(ref handle);
                }

                ErrorLog.WriteLine("Connect Status: " + status);
                if (status == 0)
                {
                    byte channel = 0;
                    byte address = 0;

                    if (ci.UseManualBridgingInfo == true)
                    {
                        channel = ci.Channel;
                        address = ci.Address;
                        AddConnectionInfoItem("Bridging Channel", "0x" + channel.ToString("X2"));
                        AddConnectionInfoItem("Bridging Address", "0x" + address.ToString("X2"));
                    }
                    else
                    {
                        ErrorLog.WriteLine("Searching for NM Discovery Parameters...");
                        UpdateConnectionStatus("Searching for NM Discovery Parameters...");
                        NMPRK.nm_discovery_parameters_t parameters = new NMPRK.nm_discovery_parameters_t();
                        status = NMPRK.NMPRK_API.GetDiscoveryParameters(handle, ref parameters);
                        if (status != NMPRK.NMPRK_API.NMPRK_SUCCESS)
                        {
                            DisplayNmprkError("GetDiscoveryParameters", status, "The server may not support Node Manager or has not implemented the 'Node Manager OEM SDR'");
                            NMPRK.NMPRK_API.Disconnect(handle);
                            ConnectThreadComplete(false);
                            return;
                        }

                        channel = parameters.channel;
                        address = parameters.address;

                        AddConnectionInfoItem("Bridging Channel", "0x" + channel.ToString("X2"));
                        AddConnectionInfoItem("Bridging Address", "0x" + address.ToString("X2"));
                        AddConnectionInfoItem("Health Event Sensor", "0x" + parameters.nmHealthEvSensor.ToString("X2"));
                        AddConnectionInfoItem("Exception Event Sensor", "0x" + parameters.nmExceptionEvSensor.ToString("X2"));
                        AddConnectionInfoItem("Operational Capabilities Sensor", "0x" + parameters.nmOperationalCapSensor.ToString("X2"));
                        AddConnectionInfoItem("Alert Threshold Exceeded Sensor", "0x" + parameters.nmAlertThresExcdSensor.ToString("X2"));
                    }

                    ErrorLog.WriteLine("NM Channel: 0x" + channel.ToString("X2"));
                    ErrorLog.WriteLine("NM Address: 0x" + address.ToString("X2"));
                    status = NMPRK.NMPRK_API.SetDefaultNmCommandBridging(handle, channel, address);
                    if (status != NMPRK.NMPRK_API.NMPRK_SUCCESS)
                    {
                        DisplayNmprkError("SetDefaultNmCommandBridging", status);
                        NMPRK.NMPRK_API.Disconnect(handle);
                        ConnectThreadComplete(false);
                        return;
                    }

                    NMPRK.nm_get_version_output_t versionOutput = new NMPRK.nm_get_version_output_t();
                    status = NMPRK.NMPRK_API.GetVersion(handle, ref versionOutput);
                    if (status == NMPRK.NMPRK_API.NMPRK_SUCCESS)
                    {
                        currentConnectionNmVersion = versionOutput.version;
                        AddConnectionInfoItem("IPMI Version", "0x" + versionOutput.ipmiVersion.ToString("X2"));
                        AddConnectionInfoItem("Node Manager Version", "0x" + versionOutput.version.ToString("X2"));
                        AddConnectionInfoItem("Major Firmware Revision", "0x" + versionOutput.majorFirmwareRevision.ToString("X2"));
                        AddConnectionInfoItem("Minor Firmware Revision", "0x" + versionOutput.minorFirmwareRevision.ToString("X2"));
                    }

                    _connectionHandle = handle;
                    _connected        = true;
                    ConnectThreadComplete(true);
                }
                else
                {
                    DisplayNmprkError("Connect", status);
                    NMPRK.NMPRK_API.Disconnect(handle);
                    ConnectThreadComplete(false);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
            }
        }
Exemplo n.º 31
0
        /// <summary>获取登录页面信息</summary>
        /// <param name="doc">Xml 文档对象</param>
        /// <returns>返回操作结果</returns>
        private string CreateLoginPage(string clientId, string redirectUri, string responseType, string scope)
        {
            // 测试地址
            // http://x10.x3platform.com/api/connect.oauth2.authorize.aspx?client_id=a70633f6-b37a-4e91-97a0-597d708fdcef&redirect_uri=https://x10.x3platform.com/api/connect.auth.back.aspx%3fclient_id%3da70633f6-b37a-4e91-97a0-597d708fdcef&response_type=code
            // http://x10.x3platform.com/api/connect.oauth2.authorize.aspx?client_id=a70633f6-b37a-4e91-97a0-597d708fdcef&redirect_uri=https://x10.x3platform.com/api/connect.auth.back.aspx%3fclient_id%3da70633f6-b37a-4e91-97a0-597d708fdcef&response_type=token

            StringBuilder outString = new StringBuilder();

            ConnectInfo connect = ConnectContext.Instance.ConnectService[clientId];

            outString.AppendLine("<!DOCTYPE HTML>");

            outString.Append("<html>");
            outString.AppendLine();
            outString.Append("<head>");
            outString.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\" />");
            outString.Append("<title>" + connect.Name + " 应用接入验证 - " + KernelConfigurationView.Instance.SystemName + "</title>");
            outString.Append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            outString.Append("<link rel=\"stylesheet\" media=\"all\" href=\"/views/templates/internal/oauth/login.css\" type=\"text/css\" />");
            outString.Append("<link rel=\"shortcut icon\" href=\"/favorite.ico\" />");
            outString.Append("<script id=\"crypto-sha1-script\" type=\"text/javascript\" src=\"/resources/javascript/crypto/rollups/sha1.js\" ></script>");
            outString.Append("</head>");

            outString.Append("<body>");

            outString.Append("<form id=\"auth-form\" name=\"authForm\" method=\"POST\" action=\"/api/connect.auth.authorize.aspx?clientId=" + clientId
                             + (string.IsNullOrEmpty(redirectUri) ? "&redirectUri=" + connect.RedirectUri : "&redirectUri=" + redirectUri)
                             + (string.IsNullOrEmpty(responseType) ? "&responseType=code" : "&responseType=" + responseType)
                             + (string.IsNullOrEmpty(scope) ? string.Empty : "&scope=" + scope) + "\" >");

            outString.Append("<div class=\"window-login-main-wrapper\" style=\"width:100%;\" >");
            outString.Append("<div class=\"window-login-form-wrapper\" style=\"margin:4px auto 0 auto; float:none;\" >");
            outString.Append("<div class=\"window-login-form-container\" >");
            outString.Append("<div class=\"window-login-form-input\" >");
            outString.Append("<span>帐号</span> ");
            outString.Append("<input id=\"loginName\" name=\"loginName\" maxlength=\"20\" type=\"text\" class=\"window-login-input-style\" value=\"\" />");
            outString.Append("</div>");
            outString.Append("<div class=\"window-login-form-input\" >");
            outString.Append("<span>密码</span>");
            outString.Append("<input id=\"originalPassword\" maxlength=\"20\" type=\"password\" class=\"window-login-input-style\" value=\"\" />");
            outString.Append("<input id=\"password\" name=\"password\" type=\"hidden\" value=\"\" />");
            outString.Append("</div>");

            // outString.Append("<div class=\"window-login-form-remember-me\" >");
            // outString.Append("<a href=\"/public/forgot-password.aspx\" target=\"_blank\" >忘记登录密码?</a>");
            // outString.Append("<input id=\"remember\" name=\"remember\" type=\"checkbox\" > <span>记住登录状态</span>");
            // outString.Append("</div>");
            outString.Append("<div class=\"window-login-button-wrapper\" >");
            outString.Append("<div class=\"window-login-button-submit\" ><a id=\"btnSubmit\" href=\"javascript:loginCheck();\" >登录</a></div>");
            // outString.Append("<div class=\"window-login-loading\" style=\"display:none;\" ><img src=\"/resources/images/loading.gif\" alt=\"登录中\" /></div>");
            outString.Append("</div>");
            // outString.Append("<div class=\"window-login-form-bottom\" >");
            // outString.Append("<a href=\"#\" >注册新帐号</a>");
            // outString.Append("</div>");
            ;

            outString.Append("</div>");
            outString.Append("</div>");
            outString.Append("</div>");

            outString.Append("</form>");
            outString.Append("</body>");
            outString.Append("</html>");
            outString.AppendLine();
            outString.AppendLine("<script type=\"text/javascript\">");
            outString.AppendLine("function loginCheck() {");
            outString.AppendLine("if (document.getElementById('loginName').value == '' || document.getElementById('originalPassword').value == '') {");
            outString.AppendLine("  alert('必须填写帐号和密码。');");
            outString.AppendLine("  return void(0);");
            outString.AppendLine("} ");
            outString.AppendLine();
            outString.AppendLine("document.getElementById('password').value = CryptoJS.SHA1(document.getElementById('originalPassword').value).toString(); ");
            outString.AppendLine();
            outString.AppendLine("document.getElementById('auth-form').submit();");
            outString.AppendLine("} ");
            outString.Append("</script>");

            return(outString.ToString());
        }
Exemplo n.º 32
0
 private static void OnUnityConnectStateChanged(ConnectInfo state)
 {
     instance.SendNotification();
 }
Exemplo n.º 33
0
        public static bool InstallApp(string appFullPath, ConnectInfo connectInfo, bool waitForDone = true)
        {
            try
            {
                // Calc the cert and dep paths
                string fileName = Path.GetFileName(appFullPath);
                string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
                string certName = Path.GetFileName(certFullPath);
                string depPath = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\";

                // Post it using the REST API
                WWWForm form = new WWWForm();

                // APPX file
                FileStream stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader reader = new BinaryReader(stream);
                form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
                stream.Close();

                // CERT file
                stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                reader = new BinaryReader(stream);
                form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
                stream.Close();

                // Dependencies
                FileInfo[] depFiles = (new DirectoryInfo(depPath)).GetFiles();
                foreach (FileInfo dep in depFiles)
                {
                    stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    reader = new BinaryReader(stream);
                    string depFilename = Path.GetFileName(dep.FullName);
                    form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
                    stream.Close();
                }

                // Credentials
                Dictionary<string, string> headers = form.headers;
                headers["Authorization"] = "Basic " + EncodeTo64(connectInfo.User + ":" + connectInfo.Password);

                // Unity places an extra quote in the content-type boundary parameter that the device portal doesn't care for, remove it
                if (headers.ContainsKey("Content-Type"))
                {
                    headers["Content-Type"] = headers["Content-Type"].Replace("\"", "");
                }

                // Query
                string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
                query += "?package=" + WWW.EscapeURL(fileName);
                WWW www = new WWW(query, form.data, headers);
                DateTime queryStartTime = DateTime.Now;
                while (!www.isDone &&
                       ((DateTime.Now - queryStartTime).TotalSeconds < TimeOut))
                {
                    System.Threading.Thread.Sleep(10);
                }

                // Give it a short time before checking
                System.Threading.Thread.Sleep(250);

                // Report
                if (www.isDone)
                {
                    Debug.Log(JsonUtility.FromJson<Response>(www.text).Reason);
                }

                // Wait for done (if requested)
                DateTime waitStartTime = DateTime.Now;
                while (waitForDone &&
                    ((DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime))
                {
                    AppInstallStatus status = GetInstallStatus(connectInfo);
                    if (status == AppInstallStatus.InstallSuccess)
                    {
                        Debug.Log("Install Successful!");
                        break;
                    }
                    else if (status == AppInstallStatus.InstallFail)
                    {
                        Debug.LogError("Install Failed!");
                        break;
                    }

                    // Wait a bit and we'll ask again
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.ToString());
                return false;
            }

            return true;
        }
Exemplo n.º 34
0
        public static bool LaunchApp(string appName, ConnectInfo connectInfo)
        {
            // Post it using the REST API
            WWWForm form = new WWWForm();
            form.AddField("user", "user");        // Unity needs some data in the form

            // Find the app description
            AppDetails appDetails = QueryAppDetails(appName, connectInfo);
            if (appDetails == null)
            {
                Debug.LogError("Appliation not found");
                return false;
            }

            // Setup the command
            string query = string.Format(kAPI_AppQuery, connectInfo.IP);
            query += "?appid=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageRelativeId));
            query += "&package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFamilyName));

            // Credentials
            Dictionary<string, string> headers = form.headers;
            headers["Authorization"] = "Basic " + EncodeTo64(connectInfo.User + ":" + connectInfo.Password);

            // Query
            WWW www = new WWW(query, form.data, headers);
            DateTime queryStartTime = DateTime.Now;
            while (!www.isDone &&
                   ((DateTime.Now - queryStartTime).TotalSeconds < TimeOut))
            {
                System.Threading.Thread.Sleep(10);
            }

            // Error
            if (!string.IsNullOrEmpty(www.error))
            {
                Debug.LogError(www.error);
                return false;
            }

            return true;
        }
Exemplo n.º 35
0
        private void btnConnect_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                btnConnect.IsEnabled = false;

                if (Connected == false)
                {
                    SaveSettings();

                    ConnectionHandle = -1;
                    Connected = false;

                    ConnectInfo ci = new ConnectInfo();
                    ci.Remote = rbRemote.IsChecked.Value;
                    ci.Ip = tbIpAddress.Text;
                    ci.User = tbUsername.Text;
                    ci.Pass = tbPassword.Password;

                    circularProgressBar1.Visibility = System.Windows.Visibility.Visible;

                    _connectThread = new Thread(ConnectThread);
                    _connectThread.Start(ci);
                }
                else
                {
                    _connectThread = new Thread(DisconnectThread);
                    _connectThread.Start();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
            }
        }
Exemplo n.º 36
0
        public static AppInstallStatus GetInstallStatus(ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_InstallStatusQuery, connectInfo.IP);
                string statusJSON = client.DownloadString(query);
                InstallStatus status = JsonUtility.FromJson<InstallStatus>(statusJSON);

                if (status == null)
                {
                    return AppInstallStatus.Installing;
                }
                else if (status.Success == false)
                {
                    Debug.LogError(status.Reason + "(" + status.CodeText + ")");
                    return AppInstallStatus.InstallFail;
                }
                return AppInstallStatus.InstallSuccess;
            }
        }
Exemplo n.º 37
0
        private void btnConnect_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                btnConnect.IsEnabled = false;
                gbConnectionType.IsEnabled = false;
                gbBmcInformation.IsEnabled = false;
                gbUseBridgingInformation.IsEnabled = false;

                if (_connected == false)
                {
                    SaveSettings();

                    _connectionHandle = -1;
                    _connected = false;
                    lbConnectionInfo.Items.Clear();

                    ConnectInfo ci = new ConnectInfo();
                    ci.Remote = rbRemote.IsChecked.Value;
                    ci.Ip = tbIpAddress.Text;
                    ci.User = tbUsername.Text;
                    ci.Pass = tbPassword.Password;
                    ci.UseManualBridgingInfo = cbUseBridgingInformation.IsChecked.Value;
                    ci.Channel = Convert.ToByte((cbNmChannel.SelectedItem as string).Substring(2), 16);
                    ci.Address = Convert.ToByte((cbNmAddress.SelectedItem as string).Substring(2), 16);

                    //circularProgressBar1.Visibility = System.Windows.Visibility.Visible;

                    _connectThread = new Thread(ConnectThread);
                    _connectThread.Start(ci);
                }
                else
                {
                    lbConnectionInfo.Items.Clear();

                    _connectThread = new Thread(DisconnectThread);
                    _connectThread.Start();
                }
            }
            catch (Exception ex)
            {
                DisplayNmprkError("Connect", -1, ex.Message);
                ErrorLog.LogException(ex);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serverUrl">pl: "opc.tcp://10.0.0.99:49310"</param>
        public Opc(string serverUrl)
        {

            // Subscribe to all the OPC DA Server events that we use
            SubscribeToOPCDAServerEvents();

            // The URL parameter describes the server and host we wish to connect to.
            // The format of the URL is rather complicated. Fortunately, we don't really
            // need to know all about that in this example. We will simply use the value
            // stored in the availableOPCServers array for the currently selected server:
            //string serverUrl = "opc.tcp://10.0.0.99:49310";

            // The clientHandle allows us to give a meaningful reference number
            // to this particular server connection. This is only used in ServerStateChanged
            // notifications. While it is a good idea to monitor and handle server
            // state changes, such as server shutdown, we will not do that in this
            // simple example. Instead, we will set the connectInfo members to have
            // the API try to keep the connection active for us. Thus, we are free 
            // to pick an arbitrary number for our client connection handle:
            int clientHandle = 1;


            // The connectInfo structure defines a number of connection parameters.
            // We will describe each of them below.
            ConnectInfo connectInfo = new ConnectInfo();

            // The LocalID member allows you to specify possible language options
            // the server may support. We will specify "en" for english.
            connectInfo.LocalId = "en";

            // The KeepAliveTime member is the time interval, in ms, in
            // which the connection to the server is checked by the API.
            connectInfo.KeepAliveTime = 60000;

            // The RetryAfterConnectionError tells the API to automatically
            // try to reconnect after a connection loss. This is nice, so 
            // we'll set to true:
            connectInfo.RetryAfterConnectionError = true;

            // The RetryInitialConnection tells the API to continue to try to
            // establish an initial connection. This is good as long as we
            // know for sure the server is really present and will likely allow
            // a connection at some point. if not, we could be here for a while
            // so best to set to false:
            connectInfo.RetryInitialConnection = false;

            // The Client Name allows the unique identification of client applications.
            // This allows the ability to easily identify multiple
            // connected clients to a server.
            connectInfo.ClientName = "CF_WebApi";

            // The connectFailed is set by the API. You should check this value
            // after a to the Connect method. We will initialize it to false in case
            // Connect throws an exception before it can be set.
            bool connectFailed = false;

            // Call the Connect API method:
            try
            {
                daServerMgt.Connect(serverUrl, clientHandle, ref connectInfo, out connectFailed);

                // Update our connection status
                if (!connectFailed)
                {
                    // Update our text box with our connection status
                    //txtConnectionStatus.Text = "Connection Succeeded";
                }
                else
                {
                    // Update our text box with our connection status
                    //txtConnectionStatus.Text = "Connection Failed";
                    throw new Exception("Connection Failed");
                }

            }
            catch (Exception ex)
            {
                connectFailed = true;
                throw;
                //MessageBox.Show("Handled Connect exception. Reason: " + ex.Message);

                // Update our text box with our connection status
                //txtConnectionStatus.Text = "Connection Failed";

                // Make sure following code knows connection failed. This value will
                // not get set when an exception occured:
            }
        }
Exemplo n.º 39
0
 private void OnConnectStateChanged(ConnectInfo state)
 {
     this.m_ConnectState = state;
     this.m_Window.UpdateState(this.RecalculateState(), false);
 }
Exemplo n.º 40
0
        public static bool IsAppRunning(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_ProcessQuery, connectInfo.IP);
                string procListJSON = client.DownloadString(query);

                ProcessList procList = JsonUtility.FromJson<ProcessList>(procListJSON);
                for (int i = 0; i < procList.Processes.Length; ++i)
                {
                    string procName = procList.Processes[i].ImageName;
                    if (procName.Contains(baseAppName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
Exemplo n.º 41
0
 /// <summary>
 /// 通知消息
 /// </summary>
 /// <param name="connectInfo"></param>
 public void Notify(ConnectInfo connectInfo)
 {
     _innerListener.Push(connectInfo);
 }
Exemplo n.º 42
0
 // Functions
 public static bool IsAppInstalled(string baseAppName, ConnectInfo connectInfo)
 {
     // Look at the device for a matching app name (if not there, then not installed)
     return (QueryAppDetails(baseAppName, connectInfo) != null);
 }
Exemplo n.º 43
0
 /// <summary>
 /// Returns a dataset override to use (if any) instead of the project's dataset.  If there is no dataset override
 /// <i>null</i> is returned and the project's dataset is used.
 /// </summary>
 /// <param name="nProjectID">Specifies the project ID associated with the trainer (if any)</param>
 /// <param name="ci">Optionally, specifies the database connection information (default = null).</param>
 protected virtual DatasetDescriptor get_dataset_override(int nProjectID, ConnectInfo ci = null)
 {
     return(null);
 }
Exemplo n.º 44
0
        public static AppDetails QueryAppDetails(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_PackagesQuery, connectInfo.IP);
                string appListJSON = client.DownloadString(query);

                AppList appList = JsonUtility.FromJson<AppList>(appListJSON);
                for (int i = 0; i < appList.InstalledPackages.Length; ++i)
                {
                    string appName = appList.InstalledPackages[i].Name;
                    if (appName.Contains(baseAppName))
                    {
                        return appList.InstalledPackages[i];
                    }
                }
            }
            return null;
        }
Exemplo n.º 45
0
 void OnUnityConnectStateChanged(ConnectInfo state)
 {
     Update();
 }
        public static bool LaunchApp(string packageFamilyName, ConnectInfo connectInfo)
        {
            // Find the app description
            AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
            if (appDetails == null)
            {
                Debug.LogError("Appliation not found");
                return false;
            }

            // Setup the command
            string query = string.Format(kAPI_AppQuery, connectInfo.IP);
            query += "?appid=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageRelativeId));
            query += "&package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFamilyName));

            // Use HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
            request.Timeout = TimeoutMS;
            request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
            request.Method = "POST";

            // Query
            using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
            {
                Debug.Log("Response = " + httpResponse.StatusDescription);
                httpResponse.Close();
            }

            return true;
        }