using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.Windows.Threading;
using System.Timers;
using System.Media;
using System.Data.SqlClient;
using System.Data;
using System.Xaml;
using System.Xml;
using System.Net.NetworkInformation;
using Ionic.Zip;
using System.Threading.Tasks;
using teboweb;
namespace MUP.Patch
{
///
/// Lógica de interacción para Patcher.xaml
///
public partial class Patcher : Window, INotifyPropertyChanged
{
public Patcher()
{
InitializeComponent();
//Conection();
//ConnectionTimerChecker();
this.DataContext = this;
}
#region Vars
bool called = true;
private string tempDownloadFolder = "";
private string processToEnd = "";
private string downloadFile = "";
private string URL = "";
private string destinationFolder = "";
private string updateFolder = System.Windows.Forms.Application.StartupPath + @"\updates\";
private string postProcessFile = "";
private string postProcessCommand = "";
/*protected delegate void SetLabelCallback(TextBlock label, string text);
public void SetLabel(TextBlock label, string text)
{
if (label.Dispatcher.CheckAccess())
{
SetLabelCallback d = new SetLabelCallback(SetLabel);
label.Dispatcher.Invoke(d, new object[] { label, text });
}
else
{
Fieldname.Text = text;
Reflesh();
InvalidateVisual();
}
}*/
#endregion
#region Network Feathers
///
/// Indicates whether any network connection is available
/// Filter connections below a specified speed, as well as virtual network cards.
///
///
/// true if a network connection is available; otherwise, false.
///
public static bool IsNetworkAvailable()
{
return IsNetworkAvailable(0);
}
///
/// Indicates whether any network connection is available.
/// Filter connections below a specified speed, as well as virtual network cards.
///
/// The minimum speed required. Passing 0 will not filter connection using speed.
///
/// true if a network connection is available; otherwise, false.
///
public static bool IsNetworkAvailable(long minimumSpeed)
{
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
// discard because of standard reasons
if ((ni.OperationalStatus != OperationalStatus.Up) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
continue;
// this allow to filter modems, serial, etc.
// I use 10000000 as a minimum speed for most cases
if (ni.Speed < minimumSpeed)
continue;
// discard virtual cards (virtual box, virtual pc, etc.)
if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
// discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
continue;
return true;
}
return false;
}
public static void ShowNetworkInterfaces()
{
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Console.WriteLine("Interface information for {0}.{1} ",
computerProperties.HostName, computerProperties.DomainName);
if (nics == null || nics.Length < 1)
{
Console.WriteLine(" No network interfaces found.");
return;
}
Console.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
Console.WriteLine();
Console.WriteLine(adapter.Description);
Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '='));
Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
Console.WriteLine(" Physical Address ........................ : {0}",
adapter.GetPhysicalAddress().ToString());
Console.WriteLine(" Operational status ...................... : {0}",
adapter.OperationalStatus);
string versions = "";
// Create a display string for the supported IP versions.
if (adapter.Supports(NetworkInterfaceComponent.IPv4))
{
versions = "IPv4";
}
if (adapter.Supports(NetworkInterfaceComponent.IPv6))
{
if (versions.Length > 0)
{
versions += " ";
}
versions += "IPv6";
}
Console.WriteLine(" IP version .............................. : {0}", versions);
// The following information is not useful for loopback adapters.
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
{
continue;
}
Console.WriteLine(" DNS suffix .............................. : {0}",
properties.DnsSuffix);
string label;
if (adapter.Supports(NetworkInterfaceComponent.IPv4))
{
IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties();
Console.WriteLine(" MTU...................................... : {0}", ipv4.Mtu);
if (ipv4.UsesWins)
{
IPAddressCollection winsServers = properties.WinsServersAddresses;
if (winsServers.Count > 0)
{
label = " WINS Servers ............................ :";
}
}
}
Console.WriteLine(" DNS enabled ............................. : {0}",
properties.IsDnsEnabled);
Console.WriteLine(" Dynamically configured DNS .............. : {0}",
properties.IsDynamicDnsEnabled);
Console.WriteLine(" Receive Only ............................ : {0}",
adapter.IsReceiveOnly);
Console.WriteLine(" Multicast ............................... : {0}",
adapter.SupportsMulticast);
Console.WriteLine();
}
}
#endregion
#region Publics Var
/* System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
SqlConnection con = new SqlConnection("workstation id=UniversityDB.mssql.somee.com;packet size=4096;user id=Nevercome2_SQLLogin_1;pwd=5rzbfru5dj;data source=UniversityDB.mssql.somee.com;persist security info=False;initial catalog=UniversityDB");
#endregion
#region Connection Feathers
//Start Connection Feathers
#region Check for connection every 5 second
private void ConnectionTimerChecker()
{
timer.IsEnabled = true;
timer.Interval = TimeSpan.FromMilliseconds(5000);
timer.Tick += OnTimerTick;
}
private void OnTimerTick(object sender, EventArgs e)
{
string ID = "1002532833";
string Password = "1223945";
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Students where ID='" + ID + "' and Password_ID='" + Password + "'", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count > 0)
{
con.Close();
}
}
catch (Exception)
{
MessageBox.Show("Connection lost attempting to reconnect", "Connection Lost");
this.Close();
}
}
#endregion
#region Confir Connection
private void Conection()
{
Patch.Logo Opening = new Patch.Logo();
Opening.Show();
string ID = "100253283";
string Password = "123945";
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Students where ID='" + ID + "' and Password_ID='" + Password + "'", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count > 0)
{
Opening.Close();
con.Close();
}
}
catch (Exception)
{
Opening.Close();
MessageBox.Show("Failed to connect with the server");
this.Close();
}
}
#endregion
//End Connection Feathers*/
#endregion
#region Patcher Feathers
private void Form1_Load(object sender, EventArgs e)
{
CUpdate.Text = "Alpha" + " " + System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
Hide();
if (called)
{
WindowState = WindowState.Normal;
Show();
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork -= new DoWorkEventHandler(backgroundWorker);
bw.DoWork += new DoWorkEventHandler(backgroundWorker);
bw.WorkerSupportsCancellation = true;
bw.RunWorkerAsync();
}
}
private void backgroundWorker(object sender, DoWorkEventArgs e)
{
preDownload();
if (called)
{
WindowState = System.Windows.WindowState.Minimized;
Show();
Fieldname.Text = "Stopping " + processToEnd;
Thread.Sleep(1000);
try
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.ProcessName == processToEnd)
{
process.Kill();
}
}
}
catch (Exception)
{ }
webdata.bytesDownloaded += Bytesdownloaded;
webdata.downloadFromWeb(URL, downloadFile, tempDownloadFolder);
Fieldname.Text = "Unzipping package...";
Thread.Sleep(1000);
unZip(tempDownloadFolder + downloadFile, tempDownloadFolder);
Fieldname.Text = "Moving files...";
Thread.Sleep(1000);
moveFiles();
Fieldname.Text = "Wrapping up...";
Thread.Sleep(1000);
wrapUp();
if (postProcessFile != "") postDownload();
}
Close();
}
private void unpackCommandline()
{
string cmdLn = "";
foreach (string arg in Environment.GetCommandLineArgs())
{
cmdLn += arg;
}
if (cmdLn.IndexOf('|') == -1)
{
try
{
called = false;
Thread.Sleep(1000);
Login.Login info = new Login.Login();
info.Show();
this.Close();
}
catch (Exception)
{
called = false;
Thread.Sleep(1000);
Login.Login info = new Login.Login();
info.Show();
this.Close();
}
}
string[] tmpCmd = cmdLn.Split('|');
for (int i = 1; i < tmpCmd.GetLength(0); i++)
{
if (tmpCmd[i] == "downloadFile") downloadFile = tmpCmd[i + 1];
if (tmpCmd[i] == "URL") URL = tmpCmd[i + 1];
if (tmpCmd[i] == "destinationFolder") destinationFolder = tmpCmd[i + 1];
if (tmpCmd[i] == "processToEnd") processToEnd = tmpCmd[i + 1];
if (tmpCmd[i] == "postProcess") postProcessFile = tmpCmd[i + 1];
if (tmpCmd[i] == "command") postProcessCommand += @" /" + tmpCmd[i + 1];
i++;
}
}
private void unZip(string file, string unZipTo)
{
try
{
// Specifying Console.Out here causes diagnostic msgs to be sent to the Console
// In a WinForms or WPF or Web app, you could specify nothing, or an alternate
// TextWriter to capture diagnostic messages.
using (ZipFile zip = ZipFile.Read(file))
{
// This call to ExtractAll() assumes:
// - none of the entries are password-protected.
// - want to extract all entries to current working directory
// - none of the files in the zip already exist in the directory;
// if they do, the method will throw.
zip.ExtractAll(unZipTo);
}
}
catch (System.Exception)
{
}
}
private void preDownload()
{
if (!Directory.Exists(updateFolder)) Directory.CreateDirectory(updateFolder);
tempDownloadFolder = updateFolder + DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) + @"\";
if (Directory.Exists(tempDownloadFolder))
{
Directory.Delete(tempDownloadFolder, true);
}
Directory.CreateDirectory(tempDownloadFolder);
unpackCommandline();
}
private void postDownload()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = postProcessFile;
startInfo.Arguments = postProcessCommand;
Process.Start(startInfo);
}
private void wrapUp()
{
if (Directory.Exists(tempDownloadFolder))
{
Directory.Delete(tempDownloadFolder, true);
}
}
private void moveFiles()
{
DirectoryInfo di = new DirectoryInfo(tempDownloadFolder);
FileInfo[] files = di.GetFiles();
foreach (FileInfo fi in files)
{
if (fi.Name != downloadFile) File.Copy(tempDownloadFolder + fi.Name, destinationFolder + fi.Name, true);
}
}
private void Bytesdownloaded(ByteArgs e)
{
Progressbar.Maximum = e.total;
if (Progressbar.Value + e.downloaded <= Progressbar.Maximum)
{
Progressbar.Value += e.downloaded;
Fieldname.Text = "Downloading Update...";
}
else
{
Fieldname.Text = "Download complete.";
}
Progressbar.Value = 0;
InvalidateVisual();
}
private void Reflesh()
{
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
System.Threading.Thread.Sleep(100);
MyValue = i.ToString();
}
});
}
private string myValue;
public string MyValue
{
get { return myValue; }
set
{
myValue = value;
RaisePropertyChanged("MyValue");
}
}
private void RaisePropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void Button_Click_1(object sender, RoutedEventArgs e)
{
new Login.Login().Show();
this.Close();
}
private void Grid_Loaded_1(object sender, RoutedEventArgs e)
{
}
}
}