Как я могу заполнить список серверов в списке из API и показать в ListView в WPF. Net Core 3.1 - PullRequest
0 голосов
/ 17 января 2020

Я создаю программное обеспечение VPN WPF, и у меня есть API для всего и, скажем, serverlist его ссылка

https://webservice.abcd.com/serverlist

Теперь у меня есть класс модели для списка серверов в виде

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; }
}
}

Теперь у меня есть сервер из нескольких стран, и я хочу показать его в окне в виде ListView, где каждый сервер можно выбрать для подключения к службе VPN. Как я могу этого достичь. Название страны, город 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();
    }



}

}

1 Ответ

0 голосов
/ 17 января 2020

Если вы используете MVVM:

Общий подход состоит в том, чтобы хранить коллекцию серверов в ObservableCollection и связывать это с ListView 'ItemsSource свойство.

Если вы не используете MVVM:

Вы можете установить / обновить свойство ListView * ItemsSource из кода за Window.

Также ...

Вы можете определить, как выглядят элементы и какие данные вы показываете, установив ListView '* ItemTemplate свойство для пользовательского DataTemplate и делать все, что вы хотите там.

Вот и пример MVVM

Окно 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>

Окно код за кодом:

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 и код класса сервера:

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; }
    }
}

Обратите внимание, что я не использую ICommand для нажатия кнопки refre sh, я бы обычно это делают.

...