Website Visitor (Visited URL) Logger Application - c#

I have made an application to log all websites visited by current PC user. This is not for a malicious use. I am making this feature for my employee monitoring software which will be licensed under proper laws.
Coming on main point, Whenever I am fetching URL from any browser such as IE. I am only getting its URL for all opened tabs. I am unable to get any tab handle for IE7+ , because of which I am unable to maintain a list of tabs for which I have already logged URL's for same tab.
Below is my code (Take a Look on Commented Code First):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WebsiteLoggerConsole
{
public class WebLogger
{
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpszClass,
string lpszWindow);
System.Threading.Timer log;
public void StartLoggin()
{
try
{
TimerCallback logcallback = new TimerCallback(LogTick);
log = new System.Threading.Timer(logcallback, null, 0, 2000);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
public void StopLogging()
{
try
{
log.Dispose();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
public void LogTick(Object stateInfo)
{
CreateLog();
}
void CreateLog()
{
try
{
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("iexplore"))
{
int val = ie.HWND;
IntPtr hwnd = new IntPtr(val);
IntPtr uihwnd = GetDirectUIHWND(hwnd);
string ddd = (ie.LocationURL) + " :::: " + (uihwnd.ToString());
Console.WriteLine(ddd);
}
}
//SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
//string filename;
//foreach (SHDocVw.InternetExplorer ie in shellWindows)
//{
// filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
// if (filename.Equals("iexplore"))
// {
// int val = ie.HWND;
// IntPtr hwnd = new IntPtr(val);
// IntPtr uihwnd = GetDirectUIHWND(hwnd);
// IntPtr tabhwnd = GetDirectUIHWND(uihwnd);
// string ddd = (ie.LocationURL) + " :::: " + (tabhwnd.ToString());
// Console.WriteLine(ddd);
// }
//}
//Process[] processlist = Process.GetProcesses();
//foreach (Process theprocess in processlist)
//{
// if (theprocess.ProcessName == "iexplore")
// {
// Console.WriteLine("Process: {0}, ID: {1}, Handle: {3}, Window name: {2}",
// theprocess.ProcessName, theprocess.Id, theprocess.MainWindowTitle, theprocess.SessionId.ToString()
// );
// }
//}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
private static IntPtr GetDirectUIHWND(IntPtr ieFrame)
{
// try IE 9 first:
IntPtr intptr = FindWindowEx(ieFrame, IntPtr.Zero, "WorkerW", null);
if (intptr == IntPtr.Zero)
{
// IE8 and IE7
intptr = FindWindowEx(ieFrame, IntPtr.Zero, "CommandBarClass", null);
}
intptr = FindWindowEx(intptr, IntPtr.Zero, "ReBarWindow32", null);
//intptr = FindWindowEx(intptr, IntPtr.Zero, "TabBandClass", null);
//intptr = FindWindowEx(intptr, IntPtr.Zero, "DirectUIHWND", null);
return intptr;
}
}
}

I provided a solution on this topic: How to write a standalone URL logger for Windows?
There I used Java, but you can do the same by using C#. I am almost sure there is a lot of good libpcap wrappers for C#.
There is a project called pcapDotNet and you can use it.
Adjusting one example:
using System;
using System.Collections.Generic;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;
namespace InterpretingThePackets
{
class Program
{
static void Main(string[] args)
{
// Retrieve the device list from the local machine
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
if (allDevices.Count == 0)
{
Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
return;
}
// Print the list
for (int i = 0; i != allDevices.Count; ++i)
{
LivePacketDevice device = allDevices[i];
Console.Write((i + 1) + ". " + device.Name);
if (device.Description != null)
Console.WriteLine(" (" + device.Description + ")");
else
Console.WriteLine(" (No description available)");
}
int deviceIndex = 0;
do
{
Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
string deviceIndexString = Console.ReadLine();
if (!int.TryParse(deviceIndexString, out deviceIndex) ||
deviceIndex < 1 || deviceIndex > allDevices.Count)
{
deviceIndex = 0;
}
} while (deviceIndex == 0);
// Take the selected adapter
PacketDevice selectedDevice = allDevices[deviceIndex - 1];
// Open the device
using (PacketCommunicator communicator =
selectedDevice.Open(65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
1000)) // read timeout
{
// Check the link layer. We support only Ethernet for simplicity.
if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
{
Console.WriteLine("This program works only on Ethernet networks.");
return;
}
// Compile the filter
using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and tcp"))
{
// Set the filter
communicator.SetFilter(filter);
}
Console.WriteLine("Listening on " + selectedDevice.Description + "...");
// start the capture
communicator.ReceivePackets(0, PacketHandler);
}
}
// Callback function invoked by libpcap for every incoming packet
private static void PacketHandler(Packet packet)
{
// print timestamp and length of the packet
Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
IpV4Datagram ip = packet.Ethernet.IpV4;
//Do your magic here using HttpRequestDatagram
}
}
}

Related

Debugging a service via IDE

I have created a program that can also be ran as a service and it will allow me to debug it as well using the following in the Program.cs startup file.
using System;
using System.Linq;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Reflection;
using System.Threading;
using crs.Includes;
using crs.Service;
using System.IO;
namespace crs
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//Convert all arguments to lower
args = Array.ConvertAll(args, e => e.ToLower());
//Create the container object for the settings to be stored
Settings.Bag = new SettingsBag();
//Check if we want to run this as a service
bool runAsService = args.Contains("-service");
//Check if debugging
bool debug = Environment.UserInteractive;
//Catch all unhandled exceptions as well
if (!debug || debug)
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
if (runAsService)
{
//Create service array
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new CRSService()
};
//Run services in interactive mode if needed
if (debug)
RunInteractive(ServicesToRun);
else
ServiceBase.Run(ServicesToRun);
}
else
{
//Start the main gui
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainGUI());
}
}
#region Functions
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
string stackTrace = ex.Message + "/n";
while (ex.InnerException != null)
{
ex = ex.InnerException;
stackTrace += ex.Message + "/n";
}
stackTrace = stackTrace.Substring(0, stackTrace.Length - 2);
string msg = "UNHANDLED EXCEPTION!/n/n" + stackTrace;
//Write all log messages to a debug log
try
{
string currentDate = DateTime.Now.ToString("yyyy-MM-dd");
string debugFilePath = AppDomain.CurrentDomain.BaseDirectory + #"debugLogs\";
string debugFilename = Application.ProductName + "-debug-" + currentDate + ".log";
if (!Directory.Exists(debugFilePath))
{
//Create the debug log files directory
Directory.CreateDirectory(debugFilePath);
}
if (!File.Exists(debugFilePath + debugFilename))
{
//Create the new file
using (StreamWriter w = File.CreateText(debugFilePath + debugFilename))
{
w.WriteLine("Debug log file for " + Application.ProductName + ".");
w.WriteLine("Created on " + currentDate + ".");
w.WriteLine("");
}
}
//Write the log message to the file
using (StreamWriter w = File.AppendText(debugFilePath + debugFilename))
{
w.WriteLine(DateTime.Now.ToString() + " :: " + msg);
}
}
catch
{ }
}
private static void RunInteractive(ServiceBase[] servicesToRun)
{
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to stop the services and end the process...");
Console.ReadKey();
Console.WriteLine();
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
//Keep the console alive for a second to allow the user to see the message.
Console.WriteLine("All services stopped.");
Thread.Sleep(1000);
}
#endregion
}
}
Everything works as expected except for the line Console.ReadKey(); under the RunInteractive() method. If I was to try and run this service manually in a console window I would have no issues what so ever, it runs great and waits for me to hit enter to start the service stopping process. However, when running it in the IDE it's spitting everything out to the DEBUG window and there is nothing for it to grab a ReadKey on.
How can I go about getting around this when debugging in the IDE? Is it possible to somehow force it to run in a command window when debugging in the IDE?
After some digging around I came up with a new class to suit my needs. Thanks for the post by Pavlo I was able to actually get text to read and write to the new console window I needed to create when one was not present.
My altered RunInteractive function from my original question:
private static void RunInteractive(ServiceBase[] servicesToRun)
{
//Account for running this application without a console window (debugging in IDE)
if (!ConsoleWindow.Exists() && !ConsoleWindow.Create())
return;
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to stop the services and end the process...");
Console.ReadKey();
Console.WriteLine();
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
//Keep the console alive for a second to allow the user to see the message.
Console.WriteLine("All services stopped.");
Thread.Sleep(1000);
}
Note: The only thing that was added here was this little bit at the top of the function.
//Account for running this application without a console window (debugging in IDE)
if (!ConsoleWindow.Exists() && !ConsoleWindow.Create())
return;
My new ConsoleWindow class:
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace crs.Includes
{
public class ConsoleWindow
{
#region Constants
private const UInt32 GENERIC_WRITE = 0x40000000;
private const UInt32 GENERIC_READ = 0x80000000;
private const UInt32 FILE_SHARE_READ = 0x00000001;
private const UInt32 FILE_SHARE_WRITE = 0x00000002;
private const UInt32 OPEN_EXISTING = 0x00000003;
private const UInt32 FILE_ATTRIBUTE_NORMAL = 0x80;
#endregion
#region WinAPI external functions
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport(
"kernel32.dll",
SetLastError = true
)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport(
"kernel32.dll",
SetLastError = true
)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport(
"kernel32.dll",
EntryPoint = "CreateFileW",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall
)]
private static extern IntPtr CreateFileW(
string lpFileName,
UInt32 dwDesiredAccess,
UInt32 dwShareMode,
IntPtr lpSecurityAttributes,
UInt32 dwCreationDisposition,
UInt32 dwFlagsAndAttributes,
IntPtr hTemplateFil
);
#endregion
#region Public class methods
public static bool Exists()
{
if (GetConsoleWindow() == IntPtr.Zero)
return false;
else
return true;
}
public static bool Create()
{
try
{
if (!AllocConsole())
throw new Exception("Error! Could not get a lock on a console window and could not create one.");
InitializeOutStream();
InitializeInStream();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
#endregion
#region Functions
private static void InitializeOutStream()
{
FileStream fs = CreateFileStream("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, FileAccess.Write);
if (fs != null)
{
StreamWriter writer = new StreamWriter(fs) { AutoFlush = true };
Console.SetOut(writer);
Console.SetError(writer);
}
}
private static void InitializeInStream()
{
FileStream fs = CreateFileStream("CONIN$", GENERIC_READ, FILE_SHARE_READ, FileAccess.Read);
if (fs != null)
Console.SetIn(new StreamReader(fs));
}
private static FileStream CreateFileStream(string name, uint win32DesiredAccess, uint win32ShareMode, FileAccess dotNetFileAccess)
{
SafeFileHandle file = new SafeFileHandle(CreateFileW(name, win32DesiredAccess, win32ShareMode, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero), true);
if (!file.IsInvalid)
{
FileStream fs = new FileStream(file, dotNetFileAccess);
return fs;
}
return null;
}
#endregion
}
}
Instead of console.write, you can create a log file in which you can log the status of the program. I recommend using the log4net nuget package.

No supported bluetooth protocol stack found

I use windows 7 and C#, .net4.6.1 in VS2017. I used bluetooth CSR 4.0 dongle and csr hormony bluetooth stack as the third party Bluetooth drivers..
I followed this to write a hcitool program :
Looking to write Bluetooth 'hcitool' equivelant in Windows
But when I tried to run the program to connect the BLE device. error occurs at this line
var dev = new BluetoothDeviceInfo(_searchAddress);
The error is : No supported bluetooth protocol stack found.
I have double checked and the parameters I pass is right(info + the device address)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1) {
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd) {
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2) {
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
var dev = new BluetoothDeviceInfo(_searchAddress);
bool isInRange = GetCanConnectTo(dev);
if (isInRange) {
PrintDevice(dev);
} else {
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try {
list = BluetoothRadio.AllRadios;
} catch (Exception) {
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list) {
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null) {
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null) {
return 0;
} else {
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices) {
if (cur.DeviceAddress == _searchAddress) {
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName) {
try {
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
} catch (Exception ex) {
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try {
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
} catch (SocketException) {
inRange = false;
}
return inRange;
}
}
}

The notorious yet unaswered issue of downloading a file when windows security is required

There is a web site: http://site.domain.com which prompts for credentials with "windows security" dialog box. So I managed to use WebBrowser control to navigate to the page and send keystrokes to enter the password - I could not find another way around.
Now I came to the point where the website generates a link to a file I want to download, it looks like: http://site.domain.com/operations/reporting/csv/Report720_2553217.csv
I tried to use WebClient to download the file but it does nothing (br is my WebBrowser control):
WebClient wb = new WebClient();
wb.Headers.Add( br.Document.Cookie);
wb.DownloadFile(link, #"report.csv");
I have been trying to find a working solution to no avail. I know the web client is not authenticated so tried to use web browser's cookie but it does not work. The cookie looks as follows:
TLTUID=61FE48D8F9B910F9E930F42D6A03EAA6; TLTSID=0B2B8EE82688102641B7E768807FA8B2; s_cc=true; s_sq=%5B%5BB%5D%5D; ASPSESSIONIDQQSTRDQS=FNPJCODCEMGFIDHFLKDBEMHO
So I have two questions:
How to allow web client to download a file accessible from web browser's session. What am I doing wrong in the above code sample?
Is there an easy way to use WebBrowser solely to download and save that file to the path and filename of my choice? Or how to do it all using WebClient or something else?
Not possible, AFAIK. WebClient and WebBrowser use different layers to access web. WebClient uses WinHTTP, WebBrowser uses UrlMon. Thus, they would have separate sessions (including the authentication cache).
That's possible, just use any of UrlMon APIs to download the file, e.g. URLDownloadToFile or URLDownloadToCacheFile. I've just answered a similar question.
On a side note, you don't have to feed in keystrokes to provide authentication credentials. You can implement IAuthenticateEx on WebBrowser site object for this. Here is more info.
So this is the working solution which meets the requirements given in my question. It automatically navigates to the specified website, authenticates and downloads a generated report. I used this Q/A as an outline.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;
using System.Web;
using System.Security.Authentication;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Security.Policy;
namespace margot_report
{
[ComImport,
Guid("00000112-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleObject
{
void SetClientSite(IOleClientSite pClientSite);
}
[ComImport,
Guid("00000118-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleClientSite
{
void SaveObject();
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void GetContainer(object ppContainer);
void ShowObject();
void OnShowWindow(bool fShow);
void RequestNewObjectLayout();
}
[ComImport,
GuidAttribute("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, out IntPtr
ppvObject);
}
[ComImport]
[Guid("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAuthenticate
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Authenticate(IntPtr phwnd,
[MarshalAs(UnmanagedType.LPWStr)] ref string pszUsername,
[MarshalAs(UnmanagedType.LPWStr)] ref string pszPassword);
}
class SelfAuthenticatingWebBrowser : WebBrowser, IOleClientSite, IAuthenticate, IServiceProvider
{
public static Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
public static Guid SID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
public const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
public const int S_OK = unchecked((int)0x00000000);
public void Authenticate(IntPtr phwnd, ref string pszUsername, ref string pszPassword)
{
Console.WriteLine("Authenticate");
pszUsername = Program.username; //
pszPassword = Program.password; //
//return S_OK;
}
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
{
//Console.WriteLine("QueryService");
int nRet = guidService.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
if (nRet == 0)
{
nRet = riid.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
if (nRet == 0)
{
ppvObject = Marshal.GetComInterfaceForObject(this,
typeof(IAuthenticate));
return S_OK;
}
}
ppvObject = new IntPtr();
return INET_E_DEFAULT_ACTION;
}
public void SaveObject()
{
throw new NotImplementedException();
}
public void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk)
{
throw new NotImplementedException();
}
public void GetContainer(object ppContainer)
{
throw new NotImplementedException();
}
public void ShowObject()
{
throw new NotImplementedException();
}
public void OnShowWindow(bool fShow)
{
throw new NotImplementedException();
}
public void RequestNewObjectLayout()
{
throw new NotImplementedException();
}
public IComponent Component
{
get { throw new NotImplementedException(); }
}
public IContainer Container
{
get { throw new NotImplementedException(); }
}
public bool DesignMode
{
get { throw new NotImplementedException(); }
}
public string Name
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
class Program
{
static bool send = true, verbose=false, clicked=false, submitted=false;
static int c = 0, t=0;
public static string filename, report, username, password;
/// <summary>
/// The URLMON library contains this function, URLDownloadToFile, which is a way
/// to download files without user prompts. The ExecWB( _SAVEAS ) function always
/// prompts the user, even if _DONTPROMPTUSER parameter is specified, for "internet
/// security reasons". This function gets around those reasons.
/// </summary>
/// <param name="pCaller">Pointer to caller object (AX).</param>
/// <param name="szURL">String of the URL.</param>
/// <param name="szFileName">String of the destination filename/path.</param>
/// <param name="dwReserved">[reserved].</param>
/// <param name="lpfnCB">A callback function to monitor progress or abort.</param>
/// <returns>0 for okay.</returns>
[DllImport("URLMON.DLL", EntryPoint = "URLDownloadToFileW", SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int URLDownloadToFile(int pCaller, string srcURL,
string dstFile, int Reserved, int CallBack);
static void Main(string[] args)
{
// HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://site.domain.com/operations/reporting/report-run.asp?reportid=720");
////webRequest.Proxy = webProxy;
string appname = Environment.GetCommandLineArgs()[0];
if (args.Count() < 1)
{
Console.WriteLine("Type: \"{0}\" -h for help on usage.\n", appname);
return;
}
if (args.Count() > 0)
foreach (var s in args)
if (s.Contains("-h") || s.Contains("/h") || s.Contains("-?") || s.Contains("/?"))
{
Console.WriteLine("\nUsage: {0} [-rfupv] <values>\n", appname);
Console.WriteLine("\n -r report_link ");
Console.WriteLine(" -f output_file ");
Console.WriteLine(" -u username ");
Console.WriteLine(" -p password ");
Console.WriteLine(" -t time_delay - seconds to wait before sending key strokes");
Console.WriteLine(" -v verbose output to console (for debugging)");
Console.WriteLine(" -h|? Display this info and exit.");
return;
}
try
{
if (args.Any(x => x.Contains("-f")))
{
int i = 0;
while (!args[i].Contains("-f")) i++;
filename =args[i + 1];
}
else filename = "report.csv";
if (args.Any(x => x.Contains("-r")))
{
int i = 0;
while (!args[i].Contains("-r")) i++;
report = args[i + 1];
}
else report = "http://site.domain.com/operations/reporting/report-run.asp?reportid=720";
if (args.Any(x => x.Contains("-u")))
{
int i = 0;
while (!args[i].Contains("-u")) i++;
username = args[i + 1];
}
else username = "";
if (args.Any(x => x.Contains("-p")))
{
int i = 0;
while (!args[i].Contains("-p")) i++;
password = args[i + 1];
}
else password = "";
if (args.Any(x => x.Contains("-t")))
{
int i = 0;
while (!args[i].Contains("-t")) i++;
t = int.Parse(args[i + 1]);
}
else t = 5;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (ex.InnerException != null) Console.WriteLine(ex.InnerException.Message);
return;
}
///////////////////////////////
//////////////////////////////////////////////////////
Console.WriteLine("start");
var th = new Thread(() => {
//WebBrowser
var wb = new SelfAuthenticatingWebBrowser(); // WebBrowser();
wb.Show(); Console.WriteLine(wb.DocumentText);
Console.WriteLine(wb.DocumentText);
wb.DocumentCompleted += browser_DocumentCompleted;
wb.NewWindow += browser_newWindow;
wb.ControlAdded += browser_ControlAdded ;
wb.LostFocus += browser_LostFocus;
wb.Navigating += browser_Navigating;
wb.FileDownload += browser_FileDownload;
//wb.Site = new MySitex();
//Console.WriteLine(wb.Site.GetService(typeof(IAuthenticateEx)));//wb.Site.Name
Console.WriteLine(wb.AllowNavigation);
wb.Navigate("about:blank");
object obj = wb.ActiveXInstance;
IOleObject oc = obj as IOleObject;
oc.SetClientSite(wb as IOleClientSite);
//this.Site = this as ISite;
System.IntPtr ppvServiceProvider;
IServiceProvider sp = wb as IServiceProvider;
sp.QueryService(ref SelfAuthenticatingWebBrowser.SID_IAuthenticate, ref SelfAuthenticatingWebBrowser.IID_IAuthenticate, out ppvServiceProvider);
wb.Navigate(report);
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
Console.WriteLine("end");
}
static void browser_Navigating(object sender, EventArgs e)
{
Console.WriteLine("navigating..." );
var s = sender as WebBrowser;
Console.WriteLine(s.DocumentTitle + s.Name);
//foreach (var x in s.Controls)
// Console.WriteLine(x.ToString());
//foreach(Form x in Application.OpenForms)
// Console.WriteLine(x.Name);
if (false)//(send)
{
send = false;
var thekeys = new Thread(() =>
{
Thread.Sleep(t*1000);
if (username != "")
{
Console.WriteLine("sending username key strokes");
SendKeys.SendWait(username);
SendKeys.SendWait("{TAB}");
Console.WriteLine("sent");
}
if (password != "")
{
Console.WriteLine("sending password key strokes");
SendKeys.SendWait(password);
SendKeys.SendWait("{ENTER}");
Console.WriteLine("sent");
}
});
thekeys.Start();
}
}
static void browser_FileDownload(object sender, EventArgs e)
{
if(verbose) Console.WriteLine("FileDownload : " + e.ToString());
var s = sender as WebBrowser;
if (verbose) Console.WriteLine(s.DocumentTitle + s.Name + s.Url); //Console.ReadKey();
}
static void browser_LostFocus(object sender, EventArgs e)
{
Console.WriteLine("lost focus : " + e.ToString());
var s = sender as WebBrowser;
Console.WriteLine(s.DocumentTitle + s.Name);
}
static void browser_ControlAdded(object sender, ControlEventArgs e)
{
Console.WriteLine("control added : " + e.ToString());
var s = sender as WebBrowser;
Console.WriteLine(s.DocumentTitle + s.Name);
}
static void browser_newWindow(object sender, CancelEventArgs e)
{
Console.WriteLine("new : " + e.ToString());
var s = sender as WebBrowser;
Console.WriteLine(s.DocumentTitle + s.Name);
}
static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br = sender as WebBrowser;
if (e.Url.ToString()=="about:blank") return;
if (br.Url == e.Url)
{
Console.WriteLine("Navigated to {0}", e.Url);
if (e.Url.ToString() == "http://site.domain.com/operations/reporting/report-generate.asp") submitted = true;
if(verbose) Console.WriteLine(br.DocumentText);
//Console.WriteLine(br.Document.Cookie);
if(!clicked)
foreach (HtmlElement x in br.Document.All)
{
// if (x.All == null)
//Console.WriteLine("|{0} {1} {2}| [{3}]\n", x.Id, x.Name, ".",x.GetAttribute("value"));
if (x.Name == "format" && x.GetAttribute("value") == "C") { Console.WriteLine("\n C L I C K !\n"); x.InvokeMember("click"); Thread.Sleep(1000); clicked = true; }
//else foreach (HtmlElement y in x.Document.All)
// Console.WriteLine("|{0} {1} {2}| [{3}]\n", y.Id, y.Name, y.OuterHtml, x.InnerText);
}
if (clicked && !submitted)
{
Console.WriteLine("submitting the report");
if (verbose) Console.WriteLine(" function at: {0}", br.DocumentText.IndexOf("function runReport()"));
//var newtext = br.DocumentText.Replace("value=\"R\" checked", "value=\"R\" ").Replace("value=\"C\"", "value=\"C\" checked");
//Console.WriteLine(" function at: {0}", br.DocumentText.IndexOf("function runReport()"));
br.Document.InvokeScript("runReport");
Console.WriteLine("done");
//Console.WriteLine(br.DocumentText);
}
//if (c == 1)
{
//Console.WriteLine(br.DocumentText);
if (verbose) Console.WriteLine(br.DocumentText.IndexOf("http://"));
if (verbose) Console.WriteLine(br.DocumentText.IndexOf(".csv"));
}
if (verbose) Console.WriteLine("c = {0}", c);
//http://site.domain.com/operations/reporting/csv/Report714_4045373.csv
if (submitted)
{
int start = br.DocumentText.IndexOf("csv/Report");
int end = 0; if (start >= 0) end = br.DocumentText.IndexOf(".csv", start);
if (start > 0 && end > start)
{
if (verbose) Console.WriteLine(br.DocumentText.Substring(start, end - start));
string link = "http://site.domain.com/operations/reporting/" + br.DocumentText.Substring(start, end - start) + ".csv";
Console.WriteLine(link);
//Console.WriteLine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
//Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
if (URLDownloadToFile(0, link, filename, 0, 0) == 0)
Console.WriteLine("The report has been saved as {0}", filename);
else
Console.WriteLine("There was a problem with downloading/saving the report {0}", report);
Application.ExitThread();
}
}
if (verbose) Console.WriteLine("cookies ? {0}, {1}, {2}", br.Document.Cookie == null, br.Document.Cookie == "", br.Document.Cookie);
c++;
if(c>4) Application.ExitThread(); // Stops the thread
}
}
}
}

Register and unregister OCX dll

Why Register a DLL?
I have a lot of basic doubts on DLLs and i have tried to put them in a listed Questions form as below:
Why do we need to register a DLL?
What happens when we register a DLL?
When i use a "LoadLibrary" in my C# code, i do not do any registration.
Whats the connection/difference between the two?
(Registering a DLL and Loading a DLL)
Can i register all the DLLs? or are there some DLLs which cannot be registered and why?
If anyone can recommend some online articles for clarifying my doubts it would be big help!
otherwise snippet code.
im using this code but it doesnt give exactly what i need, thats why i asked here....
its working fine in 32-bit machine but it gives denied path error in 64 bit machine
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.Runtime.InteropServices;
using System.Security;
using System.Management;
using System.IO;
using CCC_DLLRegistar.LoadLibrary;
using System.Security.Principal;
using System.Diagnostics;
namespace CCC_DLLRegistar
{
public partial class Form1 : Form
{
#region Is64BitOperatingSystem (IsWow64Process)
public static bool Is64BitOperatingSystem()
{
if (IntPtr.Size == 8) // 64-bit programs run only on Win64
{
return true;
}
else // 32-bit programs run on both 32-bit and 64-bit Windows
{
// Detect whether the current process is a 32-bit process
// running on a 64-bit system.
bool flag;
return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
IsWow64Process(GetCurrentProcess(), out flag)) && flag);
}
}
static bool DoesWin32MethodExist(string moduleName, string methodName)
{
IntPtr moduleHandle = GetModuleHandle(moduleName);
if (moduleHandle == IntPtr.Zero)
{
return false;
}
return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule,
[MarshalAs(UnmanagedType.LPStr)]string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
#endregion
#region Is64BitOperatingSystem (WMI)
public static bool Is64BitOperatingSystem(string machineName,
string domain, string userName, string password)
{
ConnectionOptions options = null;
if (!string.IsNullOrEmpty(userName))
{
options = new ConnectionOptions();
options.Username = userName;
options.Password = password;
options.Authority = "NTLMDOMAIN:" + domain;
}
// Else the connection will use the currently logged-on user
// Make a connection to the target computer.
ManagementScope scope = new ManagementScope("\\\\" +
(string.IsNullOrEmpty(machineName) ? "." : machineName) +
"\\root\\cimv2", options);
scope.Connect();
ObjectQuery query = new ObjectQuery(
"SELECT AddressWidth FROM Win32_Processor");
// Perform the query and get the result.
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject queryObj in queryCollection)
{
if (queryObj["AddressWidth"].ToString() == "64")
{
return true;
}
}
return false;
}
#endregion
public Form1()
{
InitializeComponent();
}
private string _RootPath = string.Empty;
private string _path = string.Empty;
private List<string> _Regfiles;
DLLHelper obj;
public string path
{
get { return _path; }
set { _path = value; }
}
public string RootPath
{
get { return _RootPath; }
set { _RootPath = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
// Solution 1. Is64BitOperatingSystem (IsWow64Process)
// Determine whether the current operating system is a 64 bit
// operating system.
bool f64bitOS = Is64BitOperatingSystem();
//Console.WriteLine("The current operating system {0} 64-bit.",
// f64bitOS ? "is" : "is not");
// Solution 2. Is64BitOperatingSystem (WMI)
// Determine whether the current operating system is a 64 bit
// operating system through WMI. The function is also able to
// query the bitness of OS on a remote machine.
try
{
f64bitOS = Is64BitOperatingSystem(".", null, null, null);
//Console.WriteLine("The current operating system {0} 64-bit.",
// f64bitOS ? "is" : "is not");
if (f64bitOS == true)
{
RootPath = "C:\\windows\\SysWow64\\";
}
else
{
RootPath = "C:\\Windows\\System32\\";
}
bool isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(WindowsBuiltInRole.Administrator) ? true : false;
if (isAdmin)
{
MessageBox.Show("you are an administrator");
}
else
{
MessageBox.Show("You are not an administrator");
}
path = Application.StartupPath + "\\CCC DLL\\";
List<string> regsvr = new List<string>();
foreach (string s in Directory.GetFiles(path, "*.*").Select(Path.GetFileName))
{
regsvr.Add(Application.StartupPath + "\\CCC DLL\\" + s);
}
foreach (string filepath in regsvr)
{
Registar_Dlls(filepath);
}
_Regfiles=new List<string>();
foreach (string s in Directory.GetFiles(path, "*.dll").Select(Path.GetFileName))
{
_Regfiles.Add(Application.StartupPath + "\\CCC DLL\\" + s);
if (DLLHelper.UnmanagedDllIs64Bit(Application.StartupPath + "\\CCC DLL\\" + s) == true)
{
MessageBox.Show("62 bit");
}
else
{
MessageBox.Show("32 bit");
}
}
foreach (string s in Directory.GetFiles(path, "*.ocx").Select(Path.GetFileName))
_Regfiles.Add(Application.StartupPath + "\\CCC DLL\\" + s);
foreach (string filepath in _Regfiles)
{
obj = new DLLHelper(filepath);
obj.DumpToFile(RootPath + obj.GetDLLName());
}
MessageBox.Show("Register Colmpleted");
}
catch (Exception ex)
{
//Console.WriteLine("Is64BitOperatingSystem throws the exception: {0}",
// ex.Message);
MessageBox.Show(ex.Message.ToString());
}
}
public void Registar_Dlls(string filePath)
{
try
{
//'/s' : Specifies regsvr32 to run silently and to not display any message boxes.
//string arg_fileinfo = "/s" + " " + "\"" + filePath + "\"";
string arg_fileinfo = RootPath +"\regsvr32.exe"+" "+ "/s" + " " + "\"" + filePath;
Process reg = new Process();
//This file registers .dll files as command components in the registry.
reg.StartInfo.FileName = "cmd.exe"; //"regsvr32.exe";
reg.StartInfo.Arguments = arg_fileinfo;
reg.StartInfo.UseShellExecute = false;
reg.StartInfo.CreateNoWindow = true;
reg.StartInfo.RedirectStandardOutput = true;
if (System.Environment.OSVersion.Version.Major >= 6)
{
reg.StartInfo.Verb = "runas";
}
reg.Start();
reg.WaitForExit();
reg.Close();
// MessageBox.Show("Successfully Registered your Ocx files");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

C# Auto Update Program

OK, I am working on a program that will automatically download an update if the versions don't match.
The problem now is that it loads the info from an XML file, but it doesn't download the files specified.
Any suggestions to improve the code are welcome as well!
Here is the complete source code:
http://www.mediafire.com/?44d9mcuhde9fv3e
http://www.virustotal.com/file-scan/report.html?id=178ab584fd87fd84b6fd77f872d9fd08795f5e3957aa8fe7eee03e1fa9440e74-1309401561
Thanks in advance for the help!
EDIT
The File to download, specified in Program.cs does not download and the program gets stuck at
currentFile = string.Empty;
label1.Text = "Preparing to download file(s)...";
Thread t = new Thread(new ThreadStart(DownloadFiles)); // Making a new thread because I prefer downloading 1 file at a time
t.Start();
and it start the "Thread t".
Code that seems to be making problems:
UpdateForm.cs
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.Net.NetworkInformation;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;
namespace LauncherBeta1
{
public partial class UpdateForm : Form
{
const int MF_BYPOSITION = 0x400;
[DllImport("User32")]
private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("User32")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("User32")]
private static extern int GetMenuItemCount(IntPtr hWnd);
private static WebClient webClient = new WebClient();
internal static List<Uri> uriFiles = new List<Uri>();
internal static Uri uriChangelog = null;
private static long fileSize = 0, fileBytesDownloaded = 0;
private static Stopwatch fileDownloadElapsed = new Stopwatch();
bool updateComplete = false, fileComplete = false;
string currentFile = string.Empty, labelText = string.Empty;
int progbarValue = 0, KBps = 0;
public UpdateForm()
{
IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
InitializeComponent();
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://raiderz.daregamer.com/updates/app_version.xml");
XmlNode xNodeVer = xdoc.DocumentElement.SelectSingleNode("Version");
FileVersionInfo fileVer = FileVersionInfo.GetVersionInfo(AppDomain.CurrentDomain.BaseDirectory + "lua5.1.dll");
int ver_app = Convert.ToInt32(fileVer.FileVersion.ToString());
int ver_xml = Convert.ToInt32(xNodeVer);
if (ver_xml == ver_app)
{
Application.Run(new Form1());
Environment.Exit(0);
}
else
{
if (ver_xml < ver_app || ver_xml > ver_app)
{
if (uriChangelog != null)
{
label1.Text = "Status: Downloading changelog...";
try
{
string log = webClient.DownloadString(uriChangelog);
log = log.Replace("\n", Environment.NewLine);
txtboxChangelog.Text = log;
}
catch (WebException ex) { }
}
foreach (Uri uri in uriFiles)
{
string uriPath = uri.OriginalString;
currentFile = uriPath.Substring(uriPath.LastIndexOf('/') + 1);
if (File.Exists(currentFile))
{
label1.Text = "Status: Deleting " + currentFile;
File.Delete(currentFile);
}
}
currentFile = string.Empty;
label1.Text = "Preparing to download file(s)...";
Thread t = new Thread(new ThreadStart(DownloadFiles)); // Making a new thread because I prefer downloading 1 file at a time
t.Start();
}
else
{
//MessageBox.Show("Client is up to date!");
Application.Run(new Form1());
Environment.Exit(0);
}
}
}
private void DownloadFiles()
{
foreach (Uri uri in uriFiles)
{
try
{
fileComplete = false;
fileDownloadElapsed.Reset();
fileDownloadElapsed.Start();
string uriPath = uri.OriginalString;
currentFile = uriPath.Substring(uriPath.LastIndexOf('/') + 1);
webClient.DownloadFileAsync(uri, currentFile);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
while (!fileComplete) { Thread.Sleep(1000); }
}
catch { continue; }
}
currentFile = string.Empty;
updateComplete = true;
}
void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progbarValue = e.ProgressPercentage;
fileSize = e.TotalBytesToReceive / 1024;
fileBytesDownloaded = e.BytesReceived / 1024;
if (fileBytesDownloaded > 0 && fileDownloadElapsed.ElapsedMilliseconds > 1000)
{
KBps = (int)(fileBytesDownloaded / (fileDownloadElapsed.ElapsedMilliseconds / 1000));
}
labelText = "Status: Downloading " + currentFile +
"\n" + fileBytesDownloaded + " KB / " + fileSize + " KB - " + KBps + " KB/s";
}
void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
progbarValue = 0;
fileComplete = true;
}
/// <summary>
/// Returns file size (Kb) of a Uri
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
private long GetFileSize(Uri uri)
{
try
{
WebRequest webRequest = HttpWebRequest.Create(uri);
using (WebResponse response = webRequest.GetResponse())
{
long size = response.ContentLength;
return size / 1024;
}
}
catch { return 1; }
}
private void timerMultiPurpose_Tick(object sender, EventArgs e)
{
if (updateComplete == true)
{
updateComplete = false;
label1.Text = "Status: Complete";
progressBar1.Value = 0;
MessageBox.Show("Update complete!!");
Application.Run(new Form1());
Environment.Exit(0);
}
else
{
progressBar1.Value = progbarValue;
label1.Text = labelText;
}
}
private void UI_FormClosing(object sender, FormClosingEventArgs e)
{
Environment.Exit(0);
}
}
}
Relevant code from Program.cs:
System.Threading.Thread.Sleep(1000); // Give the calling application time to exit
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://raiderz.daregamer.com/updates/app_version.xml");
XmlNode xNodeVer = xdoc.DocumentElement.SelectSingleNode("Loc");
string ver_xml = Convert.ToString(xNodeVer);
args = new string[2];
args[0] = "Changelog=http://raiderz.daregamer.com/updates/changelog.txt";
args[1] = "URIs=" + ver_xml;
if (args.Length == 0)
{
MessageBox.Show("Can not run program without parameters", "Error");
return;
}
try
{
foreach (string arg in args)
{
if (arg.StartsWith("URIs="))
{
string[] uris = arg.Substring(arg.IndexOf('=') + 1).Split(';');
foreach (string uri in uris)
{
if (uri.Length > 0)
{
UpdateForm.uriFiles.Add(new Uri(uri));
}
}
}
else if (arg.StartsWith("Changelog="))
{
UpdateForm.uriChangelog = new Uri(arg.Substring(arg.IndexOf('=') + 1));
}
}
}
catch { MessageBox.Show("Missing or faulty parameter(s)", "Error"); }
I've not downloaded or reviewed your code, but if this is all C# based and on the v2.0 framework or higher you may want to check in to using ClickOnce. It will handle much of the auto updating for you and even allow users to continue using the program if they are offline and unable to connect to your update server.

Categories