using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Configuration; using System.ServiceModel.Configuration; using System.Text.RegularExpressions; using QMAPP.WinForm.Common; namespace QMAPP.WinForm { public partial class ServerSwitch : Form { const string _AddrRegex = "(?<=//)\\S+(?=:)"; public ServerSwitch() { InitializeComponent(); } private void ServerSwitch_Load(object sender, EventArgs e) { cbServer.DataSource= ConfigurationManager.AppSettings["ServerHosts"].Split('|'); //cbServer.Items.Add("10.123.4.15"); //cbServer.Items.Add("10.123.4.15"); LoadServiceHost(); } private void LoadServiceHost() { Configuration cfg = ConfigurationManager.OpenExeConfiguration(""); var clientSecion = cfg.GetSection("system.serviceModel/client") as ClientSection; txtWCFUrl.Text = GetEndointByName(clientSecion, "BasicHttpBinding_IGeneralService").Address.Host; txtOPCUrl.Text = GetEndointByName(clientSecion, "NetTcpBinding_IOpcService").Address.Host; } private ChannelEndpointElement GetEndointByName(ClientSection section, string endpointname) { foreach (ChannelEndpointElement endpoint in section.Endpoints) { if (string.Equals(endpoint.Name, endpointname)) { return endpoint; } } return null; } private string GetServerFromURL(string url) { var servermatch= System.Text.RegularExpressions.Regex.Match(url, _AddrRegex); if (servermatch != null&&servermatch.Success) { return servermatch.Value; } return ""; } private void btnSwitchSave_Click(object sender, EventArgs e) { Configuration cfg = ConfigurationManager.OpenExeConfiguration(""); var clientSecion = cfg.GetSection("system.serviceModel/client") as ClientSection; if (cbChangeWCF.Checked) { ReplaceServerHost(clientSecion, "BasicHttpBinding_IGeneralService"); ReplaceServerHost(clientSecion, "BasicHttpBinding_ILoginService"); } if (cbChangeOPC.Checked) { ReplaceServerHost(clientSecion, "NetTcpBinding_IOpcService"); } cfg.Save(ConfigurationSaveMode.Modified, false); this.Close(); } private void ReplaceServerHost(ClientSection clientSecion,string endpointname) { var endpoint = GetEndointByName(clientSecion, endpointname); string url = Regex.Replace(endpoint.Address.ToString(), _AddrRegex, cbServer.Text); endpoint.Address = new Uri(url); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } } }