简体   繁体   English

如何从 Api 填充列表中的服务器列表并在 WPF .Net Core 3.1 中的 ListView 中显示

[英]How can I populate Servers List in List from Api and show in ListView in WPF .Net Core 3.1

I am creating VPN WPF software and I have APIs for everything and lets say serverlist its link is我正在创建 VPN WPF 软件,并且我拥有适用于所有内容的 API,可以说serverlist的链接是

https://webservice.abcd.com/serverlist https://webservice.abcd.com/serverlist

Now I have model class for server list as现在我有服务器列表的模型类

using System;
using System.Collections.Generic;
using System.Text;

namespace VirtualPN.Model
{
class ServerModel
{
    public string error { get; set; }
    public string message { get; set; }
    public Server[] servers { get; set; }
}

public class Server
{
    public string SID{ get; set; }
    public string Scountry { get; set; }
    public string Sdns { get; set; }
    public string Sport { get; set; }
    public string Spsk { get; set; }
    public string pptp { get; set; }
    public string l2tp { get; set; }
    public string tcp { get; set; }
    public string udp { get; set; }
    public string openconnect { get; set; }
    public string ikev2 { get; set; }
    public string sstp { get; set; }
    public string p2p { get; set; }
    public string videostreaming { get; set; }
    public string security { get; set; }
    public string voip { get; set; }
    public string enable { get; set; }
    public string maintmode { get; set; }
    public string iso { get; set; }
    public string free { get; set; }
    public string recent { get; set; }
    public string time { get; set; }
    public string fav { get; set; }
    public int Pingrate { get; set; }
    public string IsFavorite { get; set; }

    public string FavProtocol { get; set; }
}
}

Now I have multiple countries server and want to show it in the window as ListView where each server is selectable to connect VPN service.现在我有多个国家/地区的服务器,并希望在窗口中将其显示为 ListView,其中每个服务器都可以选择连接 VPN 服务。 How can I achieve that.我怎样才能做到这一点。 Country Name, City DNS is Important .国家名称,城市 DNS 很重要

using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.Collections;
using VirtualPN.Model;
namespace VirtualPN.Classes
{
class Global
{
    public static ServerModel sm = new ServerModel();
    public static Web_Service service = new Web_Service();
    static ArrayList nic_arr = new ArrayList();
    static bool IsdnsStatic = false;




    public Global()
    {


    }


    public class ServerType
    {
        public static string type
        {
            get; set;
        }
    }

    public static ServerModel getModel()
    {
        return sm;
    }

    public static Web_Service GetService()
    {
        return service;
    }

    public class _Server : Server
    {

        public string SId { get; set; }
        public string ServerCountry { get; set; }
        public string SDNS { get; set; }

        public string Siso { get; set; }
        public string SKey { get; set; }
        public string Sport { get; set; }
        public string Spptp { get; set; }
        public string Sl2tp { get; set; }
        public string Stcp { get; set; }
        public string Sudp { get; set; }
        public string SopenConnect { get; set; }
        public string Sikev2 { get; set; }
        public string Sstp { get; set; }
        public string Sp2p { get; set; }
        public string Svideostreaming { get; set; }
        public string Svoip { get; set; }
        public string Ssecurity { get; set; }
        public int Spingrate { get; set; }
        public string GroupName { get; set; }
        public string SIsFavorite { get; set; }
        public string IsFree { get; set; }
        public string IsRecent { get; set; }
        public string SIsTime { get; set; }
        public string Smaintmode { get; set; }


    }


    public ServerModel getServerModel
    {
        get; set;

    }


    public static string Account_Person_Name
    {
        get; set;

    }

    public static double RemainingDays
    {
        get; set;

    }

    public static DateTime DueDate
    {
        get; set;
    }

    public static bool IsfreeAccount
    {
        get; set;
    }

    public static string AccountType
    {
        get; set;
    }

    public static double TotalSubscriptionDays
    {
        get; set;
    }


    public class UrlItems
    {
        public int id { get; set; }
        public string url { get; set; }
    }



    public static void Window_Closing()
    {
        Process.GetCurrentProcess().Kill();
    }


    public static string UserName { get; set; }
    public static string password { get; set; }

    public static string GetActiveIp()
    {
        var data = Task.Run(() => Web_Service.GetIPData()).Result;
        var model = Web_Service.Map_IPModel(data.ToString());

        var ip = model.ip;

        return ip;
    }

    public static string GetActiveLocation()
    {
        var data = Task.Run(() => Web_Service.GetIPData()).Result;
        var model = Web_Service.Map_IPModel(data.ToString());

        var ip = model.country;

        return ip;
    }

    public static DateTime GetLiveDate()
    {

        var data = Task.Run(() => Web_Service.GetLiveDate()).Result;

        DateTime reg = DateTime.Parse(data);

        return reg.Date;
    }

    public static bool IsValidIpAddress(string paddress)
    {
        if (string.IsNullOrWhiteSpace(paddress))
            return false;

        var splitValues = paddress.Split('.');
        if (splitValues.Length != 4)
            return false;

        byte tempForParsing;

        return splitValues.All(r => byte.TryParse(r, out tempForParsing));
    }
    public static void Disable_Network()
    {
        // Interaction.Shell("cmd.exe /c" + value);
        string targetURL = "netsh advfirewall firewall add rule name = Block All Traffic dir =in action = allow port enable = yes remoteip = 5, 46, 48 - 1722, 1724 - 65535,LocalSubnet profile = public";

        var psi = new ProcessStartInfo
        {
            FileName = targetURL,
            UseShellExecute = true
        };
        Process.Start(psi);




    }


    public static void Activate_KillSwitch()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {


            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {
                    string targetURL = "netsh interface set interface " + ni.Name + " DISABLED";

                    var psi = new ProcessStartInfo
                    {
                        FileName = targetURL,
                        UseShellExecute = true
                    };
                    Process.Start(psi);
                    nic_arr.Add(ni.Name);
                    // Interaction.Shell("cmd.exe /c" + vpnKillString, Constants.vbHide;

                }


            }
        }
    }

    public static void EnableKillSwitch()
    {
        string targetURL = "netsh advfirewall firewall del rule name = 'BlockOutbound'";

        var psi = new ProcessStartInfo
        {
            FileName = targetURL,
            UseShellExecute = true
        };
        Process.Start(psi);
    }

    public static List<_Server> ServerListGlobal { get; set; }
    public static List<_Server> FavoriteServerListGlobal { get; set; }
    public static List<_Server> RecentServerListGlobal { get; set; }

    public static string ethernetIp
    {
        get; set;
    }

    public static DateTime CurrentDate
    {
        get; set;
    }

    public static string ethernetFXIp
    {
        get; set;
    }

    public static string ethernetTIp
    {
        get; set;
    }


    public static string wirelessIP
    {
        get; set;
    }

    public static void getAdaptersIP()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {


            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        ethernetIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();

                    }


                }
                else if (ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        ethernetFXIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                    }
                }

                else if (ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        {
                            ethernetTIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                        }
                    }
                }

                else if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        wirelessIP = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                        if (ni.GetIPProperties().GetIPv4Properties().IsDhcpEnabled)
                        {
                            if (ni.GetIPProperties().DhcpServerAddresses.FirstOrDefault().ToString() != ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString())
                            {

                                dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                                IsdnsStatic = true;
                            }
                        }
                        else
                        {
                            dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                            IsdnsStatic = true;
                        }



                    }


                }

            }


        }
    }

    public static string dnsStatic
    { get; set; }

    public static string vpndnsServer
    { get; set; }

    public static void dnsLeakFix()
    {
        IsdnsStatic = false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {

            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                string targetURL = "ipconfig /flushdns";

                var psi = new ProcessStartInfo
                {
                    FileName = targetURL,
                    UseShellExecute = true
                };
                Process.Start(psi);


                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {
                    if (ni.GetIPProperties().GetIPv4Properties().IsDhcpEnabled)
                    {
                        if (ni.GetIPProperties().DhcpServerAddresses.FirstOrDefault().ToString() != ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString())
                        {

                            dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                            IsdnsStatic = true;
                        }
                    }
                    else
                    {
                        dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                        IsdnsStatic = true;
                    }



                    string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" static 8.8.8.8 both";
                    Process.Start(dnsFix);
                    //Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);
                }


            }


        }


        Messagebox box = new Messagebox("DNS Leak has been fixed!. Enjoy your browsing...");
        box.ShowInTaskbar = false;
        box.ShowDialog();
    }

    public static void dnsLeak_Release()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {

            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                string targetURL = "ipconfig /flushdns";

                var psi = new ProcessStartInfo
                {
                    FileName = targetURL,
                    UseShellExecute = true
                };
                Process.Start(psi);

                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {

                    if (IsdnsStatic == false)
                    {
                        string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" dhcp";
                        Process.Start(dnsFix);


                   ////     Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);
                    }
                    else if (IsdnsStatic == true)
                    {
                        string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" dhcp";
                        Process.Start(dnsFix);

                       //Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);


                    }


                   Usercredentials.Default.IsDNSLeakEnabled = false;
                   Usercredentials.Default.Save();

                }

            }
        }
        Messagebox box = new Messagebox("DNS settings has been set to default.");
        box.ShowInTaskbar = false;
        box.ShowDialog();
    }



}

} }

If you're using MVVM:如果您使用的是 MVVM:

The general approach is to hold the collection of servers in an ObservableCollection and bind that to the ListView 's ItemsSource property.一般方法是将服务器集合保存在ObservableCollection并将其绑定到ListViewItemsSource属性。

If you're not using MVVM:如果您不使用 MVVM:

You can set/update the ListView 's ItemsSource property from the code behind of the Window .您可以从Window背后的代码设置/更新ListViewItemsSource属性。

Also...还...

You can define how the items look and what data you're showing by setting the ListView 's ItemTemplate property to a custom DataTemplate and doing whatever you want there.您可以通过将ListViewItemTemplate属性设置为自定义DataTemplate并在其中执行任何操作来定义项目的外观和显示的DataTemplate

Here's and MVVM example这是 MVVM 示例

Window XAML code:窗口 XAML 代码:

<Window x:Class="ExampleApp.ServerView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="ServerView" Height="450" Width="800">
    <Grid>
        <ListView ItemsSource="{Binding Servers}" SelectedItem="{Binding SelectedServer}" SelectionMode="Single">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Border Padding="5">
                        <StackPanel>
                            <TextBlock Text="{Binding CountryName, StringFormat='Country: {0}'}"  />
                            <TextBlock Text="{Binding CityDns, StringFormat='DNS: {0}'}" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Content="Refresh" Click="BtnRefresh_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" Padding="10"/>
    </Grid>
</Window>

Window code behind code:代码背后的窗口代码:

using System.Windows;

namespace ExampleApp
{
    public partial class ServerView : Window
    {
        private readonly ServerViewModel _model;
        public ServerView()
        {
            InitializeComponent();
            _model = new ServerViewModel();
            DataContext = _model;
        }

        private void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            _model.ReloadServers();
        }
    }
}

ViewModel and Server class code: ViewModel 和 Server 类代码:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ExampleApp
{
    public class ServerViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Server> Servers { get; set; } = new ObservableCollection<Server>();

        private Server _selectedServer;
        public Server SelectedServer
        {
            get => _selectedServer;
            set
            {
                if(_selectedServer != value)
                {
                    _selectedServer = value;
                    OnPropertyChanged();
                    SelectedServerChanged();
                }
            }
        }

        public void SelectedServerChanged()
        {
            //do whatever you need to do when the selected server changes here...
            System.Console.WriteLine($"The selected server has changed: {SelectedServer.CountryName}");
        }

        public void ReloadServers()
        {
            var servers = DownloadServers();

            Servers.Clear();
            foreach (var server in servers)
            {
                Servers.Add(server);
            }
        }

        private List<Server> DownloadServers()
        {
            //pretend we're downloading the list of servers here...
            return new List<Server>
            {
                new Server { CityDns = "Some DNS", CountryName = "England" },
                new Server { CityDns = "Some other DNS", CountryName = "China" },
                new Server { CityDns = "Another DNS", CountryName = "United States" }
            };
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class Server
    {
        public string CountryName { get; set; }
        public string CityDns { get; set; }
    }
}

Note that I'm not using an ICommand for the refresh button click, I would normally do that.请注意,我没有使用ICommand来单击刷新按钮,我通常会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 .Net Core 3.1 WPF 中运行交互外壳 - How can I run Interaction Shell in .Net Core 3.1 WPF 如何在 Asp Net Core 3.1 Web API 中的派生类型列表上实现数据验证属性 - How do I implement data validation attributes on a list of derived types in Asp Net Core 3.1 Web API .Net Core 3.1 下拉列表显示现有数据 - .Net Core 3.1 Dropdown list to show existing data 如何在 WPF .Net Core 3.1 中将 API 连接到我的项目 - How to connect API to my project in WPF .Net Core 3.1 按属性分组列表 .NET Core 3.1 使用 Fluent API - Grouping list by property .NET Core 3.1 using Fluent API 可空列表参数 in.Net Core 3.1 Web API - Nullable List Parameter in .Net Core 3.1 Web API 如何从 razor 查看带有动态列表的 model 中的列表? ASP.NET 内核 3.1 - How to submit from a razor view a list in a model with dynamic list? ASP.NET Core 3.1 如何在 .NET Core API 中将列表显示到具有其他信息的视图中? - How to show a list into a view with other info in .NET Core API? 如何从 .net Core 3.1 dll (WPF) 访问 Dispatcher - How to access the Dispatcher from a .net Core 3.1 dll (WPF) 我可以使用列表吗<T>和一个列表<Expression>填充一个wpf 数据网格? - Can I use a List<T> and a List<Expression> to populate a wpf datagrid?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM